Assuming I have an enum:
enum Cars {
Volvo = 'Volvo',
Hyundai = 'Hyundai',
Kia = 'Kia',
Tesla = 'Tesla'
}
I want to define an interface or a type, which should have every enum value as a key (types for them may be different or same):
interface CarToFactory {
[Cars.Volvo]: SwedishFactoryType,
[Cars.Hyundai]: KoreanFactoryType,
[Cars.Kia]: KoreanFactoryType,
// <- Error: Missing Cars.Tesla
}
So adding a new car should throw an error unless you add a mapping to factory.
I tried to define an interface that extends Record<Cars, Factory>, but this doesn't give an error on missing property.
Also, the usage may not be obvious, but I have another interface with generic param, like:
interface CarPassport<TCar extends Cars> {
company: TCar,
manufacturer: CarToFactory[TCar],
year: number,
}
This is not a question about defining JS objects, I need to solve it on TS side
Here I think the best approach is to split responsibilities:
carToFactory) responsible for mappingCarstoFactoryType, and it will enable you to have a correct inference and not a generic typeFactoryTypeinCarPassport.manufactureras you would have using a simpleRecord<Cars, FactoryType>.carToFactorymatch all the entries ofCars.The mapped type
{ [C in Cars]: typeof carToFactory[K] }ensure that allCare incarToFactoryand thetypeof carToFactory[K]part allows typescript to infer the rightFactoryTypeHere there is a playground with the code