I am running this code and would love if TS was able to recognize that the object property may be undefined, but it doesn't. Instead the browser errors out.
const carInfo = {
mercedes: {
classification: 'luxury',
color: 'blue',
year: 2022,
},
lamborghini: {
classification: 'sports',
color: 'red',
year: 1975,
},
tesla: {
classification: 'electric',
color: 'silver',
year: 2015,
}
}
const getCarInfo = (make: string) => {
const car = carInfo[make];
if (car.classification) {
console.log('The classification is', car.classification)
} else {
console.log('Cant get the classification')
}
}
When I try to call the function with an unsupported property such as getCarInfo('ford') , the browser errors out TypeError: Cannot read properties of undefined (reading 'classification'), which is what I expect, but I thought that TS would warn me that car may be undefined so I should access car.classification as car?.classification instead.
Is there any way I can make that happen in TS?