如何处理可能为undefined的TypeScript嵌套对象

huangapple go评论161阅读模式
英文:

How do I handle typescript nested objects being possibly undefined

问题

我有一个对象的对象,为其定义了类型别名,并尝试对其进行映射,但我卡在如何处理以下错误上:

无法调用可能为'undefined'的对象。

这是我的用例:

type apple = {
  color: string
  size: string
}
type apples = {
  [x: string]: apple
}

const appleObj: apples = {
  1: {
    color: "red",
    size: "small",
  },
  2: {
    color: "green",
    size: "large",
  },
}

appleObj.map(({ color, size }) => {
  console.log(color, size)
})

请帮助 如何处理可能为undefined的TypeScript嵌套对象

英文:

I have an object of objects that I've defined type aliases for and am trying to map through it but I'm stuck as how to handle the following error:

> Cannot invoke an object which is possibly 'undefined'.

Here is my use case:

type apple = {
  color: string
  size: string
}
type apples = {
  [x: string]: apple
}

const appleObj: apples = {
  1: {
    color: "red",
    size: "small",
  },
  2: {
    color: "green",
    size: "large",
  },
}

appleObj.map(({ color, size }) => {
  console.log(color, size)
})

Please help 如何处理可能为undefined的TypeScript嵌套对象

答案1

得分: 1

不能直接在对象上使用map,我们需要使用Object.keys来映射对象,如下所示。

Object.keys(appleObj).map(key => {
    const apple = appleObj[key];
    console.log(apple.color, apple.size);
});
英文:

You can't use map on object directly, we need to use Object.keys to map the object as below.

Object.keys(appleObj).map(key => {
    const apple = appleObj[key];
    console.log(apple.color, apple.size);
});

huangapple
  • 本文由 发表于 2023年3月12日 17:24:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75712168.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定