I am currently working on a project where I am creating a type that maps different enum types to expected data types. My goal is to accurately determine the correct type of the data through type inference.
enum Car {
BMW,
Toyota,
Fiat
}
type CarWithData =
| {
type: Car.BMW;
data: {
doucheFactor: number;
};
}
| {
type: Car.Toyota;
data: {
dadFactor: number;
};
}
| {
type: Car.Fiat;
data: {
dadFactor: number;
};
};
function handleCar(car: CarWithData) {
switch (car.type) {
case Car.BMW:
console.log(`BMW owner found with douche factor of: ${car.data.doucheFactor}`);
console.log(`DadFactor: ${car.data.dadFactor}`); // TypeError as expected / intended;
break;
default:
console.log(`Toyota / Fiat owner found with dad factor of: ${car.data.dadFactor}`);
}
}
function getDadFactor(car: CarWithData): number {
return car.data.dadFactor ?? -1; // Property "dadFactor" does not exist on type CarWithData
}
handleCar({ type: Car.BMW, data: { doucheFactor: 900 } });
getDadFactor({ type: Car.Fiat, data: { dadFactor: 10} });
In this scenario, my code successfully utilizes type inference in the switch statement within handleCar
. However, an issue arises in the getDadFactor
function where a TypeError is thrown due to "dadFactor" not being recognized under the type CarWithData. Can you suggest a more optimal solution than including all possible fields with type never in a union?