我想创建一个接受枚举的通用打字稿类型,然后验证该类型中的键是否属于该枚举。我正在寻找这样的东西:
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',
};
尽管[key in T]
工作正常,但[key in Planes]
语法无效。
答案 0 :(得分:1)
为此,我使用extends
关键字对枚举进行了合并:
type ImageList<T extends Cars | Planes> = {
[key in T]: string;
}