I want to define the object type that I download from my database.
type ActiveOrders = {[orderId: string]: {name: string; price: number}}
const activeOrders: ActiveOrders = {
'orderId1': {name: 'apple', price: 123},
'orderId2': {name: 'banana', price: 123},
'orderId3': {name: 'tesla', price: 99999999},
}
Following code is fine, and my orderData is guaranteed to exist.
for(const orderId in activeOrders) {
const orderData = activeOrders[orderId]
// This is fine, orderData is guaranteed to exist
const {name, price} = orderData
}
This is NOT fine, but typescript is not giving me any error. someRandomId
can come from anywhere such as user entered value.
const orderData2 = activeOrders['someRandomId']
// This is NOT fine, orderData2 is possibly undefined, but typescript says it is guaranteed to exist.
const {name, price} = orderData2
I can change my type to following but I want to avoid as it will mess up my for-in loop.
type ActiveOrders = {[orderId: string]: {name: string; price: number} | undefined}
Is there more elegant solution to this?