当我尝试检查对象内字段的值时,得到了ts error: Object is possibly 'undefined'.(2532)
错误,其中对象的键可以是枚举的值。
下面是重现此问题的一个小示例:
enum Fruits {
Apple = "Apple",
Bannana = "Bannana",
// and a lot more…
}
type fruitsInfo = {
[key in Fruits]? : { cal: number, carb: number, }
};
type numberOfFruits = {
[key in Fruits]? : number
};
function makeMeal(info : fruitsInfo, fruits : numberOfFruits) {
for (const keyStr in info) {
const key = keyStr as Fruits;
if (fruits[key] > 2) {
console.log("You eat a lot!")
}
}
}
在TSPlayground跑步。
当然这只是一个例子,我的代码要复杂得多,我不能通过删除?
来改变fruitsInfo
或numberOfFruits
的结构,因为事实是,对象可能不包含所有内容。
我唯一确定的是:我确信,如果某个密钥位于info
中,则它也位于fruits
中
1条答案
按热度按时间moiiocjp1#
您的错误是
Object is possibly 'undefined'.(2532)
所以你基本上
您需要通过
!
子句将undefined
细化为NonNullable
或细化为number