Radex
Radex

Reputation: 8587

Property not found while object destructing typescript

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

Answers (1)

Andrew Nolan
Andrew Nolan

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

Related Questions