Flavor is a distinct union, represented as a value of an Object.
While attempting to execute this idea, it functions in js, however, TypeScript does not approve. ts playground link
Desired Outcome: For TypeScript to comprehend discriminated unions within loops, much like it comprehends them independently
type Flavor = ({
natural: true,
naturalComponent : string
}) | ({
natural: false,
artificialComponent: string
})
type IceCreamType = Record<string, Flavor>
const IceCreams: IceCreamType = {
CokeIceCream: {
natural:false,
artificialComponent: 'Coke'
},
Vanilla: {
natural: true,
naturalComponent: 'Vanilla Extract'
},
Mango: {
natural: true,
naturalComponent: 'Mango Fruit'
}
}
const iceCreamKeys = Object.keys(IceCreams)
iceCreamKeys.forEach( item => {
if(IceCreams[item].natural){
console.log(IceCreams[item].naturalComponent) // TypeScript reports "Property doesn't exist.."
}
})
if(IceCreams.Mango.natural){
console.log(IceCreams.Mango.naturalComponent) // This works without an issue
}