I am trying use an array containing multiple different types and have TypeScript infer the proper type for each element:
type House = {
street: string;
zipCode: number;
}
type Car = {
make: string;
model: string;
year: number
}
const things: (House | Car)[] = [{
street: '123 Fake Street',
zipCode: 12345
}, {
make: 'Tesla',
model: 'Model X',
year: 2022
},
{
/* any other 'Car' or 'House' */
}]
things[1].year; // <---- Why doesn't TypeScript know it is a "Car" type and shows me an error here?
Is there an easy way to help TypeScript with knowing the type without explicitly casting the array element?