Reputation: 8587
I am using object deconstruct on a map, but I receive this error. How do I handle the case that the object in the map is undefined?
const { amount } = data.get(id)
but I receive this error:
Property 'amount' does not exist on type 'Readonly<{ amount: number; article: string; }>
Upvotes: 0
Views: 142
Reputation: 2107
You will need to do a check if Map.get(k)
is undefined
. The value returned from .get(k)
is a union of whatever the value that gets set and undefined
.
interface IClothing {
amount: number;
article: string;
}
const m: Map<number, IClothing> = new Map()
m.set(1, { amount: 10, article: 'shirt' })
const p1 = m.get(1)
const { amount } = p1 !== undefined ? p1 : {amount: 0};
So in my example, m.get(1)
is a union of IClothing
and undefined
and a check should be done to ensure its not.
Upvotes: 1