[英]Pass enum to a generic class in typescript
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. 尽管
[key in Planes]
可以正常工作,但[key in Planes]
[key in T]
语法无效。
To do that, I did a union of the enums with the extends
keyword: 为此,我使用
extends
关键字对枚举进行了合并:
type ImageList<T extends Cars | Planes> = {
[key in T]: string;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.