我希望记录中某些键的类型是严格的,其余键的类型是自由的。
type Make "Volvo" | "Polestar" | "Saab";
interface Car {
make: Make;
horsePower: number;
allWheelDrive: boolean;
...
}
我想让它接受
{
make: "Saab",
horsePower: 232,
allWheelDrive: true,
colour: "blue",
trim: "leather
}
但不
{
make: "Daimler",
horsePower: 199,
allWheelDrive: false,
colour: "blue",
trim: "leather
}
如何写Car
接口和打印稿能够这样做吗?
我认为枚举最适合你。
enum Make {
Volvo="Volvo",
Polester="Polseter",
Saab="Saab"
}
interface Car {
make: Make;
horsePower: number;
allWheelDrive: boolean;
}
我觉得你应该有"专门化"&;变体。
每个变体都有特定的字段和类型,最后还有一个更"通用"的;一:
interface FooCar {
make: 'foo';
something: false;
extraField: string;
}
interface BarCar {
make: 'bar';
something: true;
}
interface BazCar {
make: 'baz';
something: boolean;
explosionProbability: number;
}
type Car =
| FooCar
| BarCar
| BazCar
| {
make: string;
something: boolean;
};