Reputation:
I want to create a generic typescript type which takes an enum and then verifies that keys in the type belong to that enum. I am looking for something like this:
enum Cars {
Toyota = 'toyota',
Lada = 'lada',
}
enum Planes {
Boeing = 'boeing',
Airbus = 'airbus',
}
type ImageList<T> = {
// `key in Planes` works, but `key in T` doesn't
[key in T]: string;
}
// And that's how I will use the type:
const images: ImageList<Planes> = {
[Planes.Boeing]: 'https://...jpg',
[Planes.Airbus]: 'https://...jpg',
};
The [key in T]
syntax is invalid, although [key in Planes]
works fine.
Upvotes: 0
Views: 78
Reputation:
To do that, I did a union of the enums with the extends
keyword:
type ImageList<T extends Cars | Planes> = {
[key in T]: string;
}
Upvotes: 1