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

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

How do I handle typescript nested objects being possibly undefined

问题

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

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

这是我的用例:

  1. type apple = {
  2. color: string
  3. size: string
  4. }
  5. type apples = {
  6. [x: string]: apple
  7. }
  8. const appleObj: apples = {
  9. 1: {
  10. color: "red",
  11. size: "small",
  12. },
  13. 2: {
  14. color: "green",
  15. size: "large",
  16. },
  17. }
  18. appleObj.map(({ color, size }) => {
  19. console.log(color, size)
  20. })

请帮助 如何处理可能为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:

  1. type apple = {
  2. color: string
  3. size: string
  4. }
  5. type apples = {
  6. [x: string]: apple
  7. }
  8. const appleObj: apples = {
  9. 1: {
  10. color: "red",
  11. size: "small",
  12. },
  13. 2: {
  14. color: "green",
  15. size: "large",
  16. },
  17. }
  18. appleObj.map(({ color, size }) => {
  19. console.log(color, size)
  20. })

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

答案1

得分: 1

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

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

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

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

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:

确定