英文:
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)
})
请帮助
英文:
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
答案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);
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论