对象销毁打字稿时找不到属性

时间:2020-02-03 12:38:02

标签: typescript

我在地图上使用对象解构,但是收到此错误。如何处理地图中的对象未定义的情况?

const { amount } = data.get(id)

但我收到此错误:

Property 'amount' does not exist on type 'Readonly<{ amount: number; article: string; }>

1 个答案:

答案 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)IClothingundefined的并集,应进行检查以确保不存在。