在 TypeScript (v4.5.4) 中,我试图通过索引签名来定义对象类型。我希望 TypeScript 强制对象中的某些子属性具有匹配的类型,但这些类型允许在顶级属性之间变化。
在下面的(非工作)示例中,我希望所有快乐的司机驾驶他们最喜欢的汽车类型。驾驶员最喜欢的汽车类型与其汽车的实际类型不匹配会导致 TypeScript 编译器错误。
type CarType = 'Minivan' | 'Sports car' | 'Sedan' ; // | 'Pickup truck' |, etc. Imagine this union type has many possible options, not just three.
type Car = {
carType: CarType
// A car probably has many additional properties, not just its type, but those are left out of this minimal example.
// The solution should be resistant to adding additional properties on `Car` (and the `Driver` type below).
};
type Driver = {
favoriteCarType: CarType
car: Car
};
/**
* Happy drivers drive their favorite car type.
*/
const happyDrivers: { [name: string]: Driver } = {
alice: {
favoriteCarType: 'Minivan',
car: {
carType: 'Minivan', // ✅ Alice drives her favorite type of car.
},
},
bob: {
favoriteCarType: 'Sports car',
car: {
carType: 'Sedan', /* ❌ Bob doesn't drive his favorite type of car!
This currently does not throw a compiler error because my types are too permissive, but I want it to. */
},
},
};
我已经尝试以我能想到的所有方式将泛型应用于索引签名和/或Car
and/orDriver
类型,但我无法让编译器强制执行驱动程序必须与其'sfavoriteCarType
完全匹配的约束。car
carType
你能帮我吗?