Encountered the
ts error: Object is possibly 'undefined'.(2532)
issue while trying to access the value of a field within an object, where the object key corresponds to a value in an Enum.
Below is a concise example to showcase this problem:
enum Fruits {
Apple = "Apple",
Bannana = "Bannana",
// and 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!")
}
}
}
Although this is just a simple demonstration, my actual code is more complex. It's important that I maintain the structure of fruitsInfo
and numberOfFruits
with the ?
, since not all keys may be present in the objects.
One thing is certain: any key existing in info
will also exist in fruits