我在地图上使用对象解构,但是收到此错误。如何处理地图中的对象未定义的情况?
const { amount } = data.get(id)
但我收到此错误:
Property 'amount' does not exist on type 'Readonly<{ amount: number; article: string; }>
答案 0 :(得分:1)
您将需要检查Map.get(k)
是否为undefined
。从.get(k)
返回的值是任何与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};
因此在我的示例中,m.get(1)
是IClothing
和undefined
的并集,应进行检查以确保不存在。