[英]Pass enum to a generic class in typescript
我想創建一個通用的打字稿類型,它接受一個枚舉,然后驗證該類型中的鍵是否屬於該枚舉。 我正在尋找這樣的東西:
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 Planes]
可以正常工作,但[key in Planes]
[key in T]
語法無效。
為此,我使用extends
關鍵字對枚舉進行了合並:
type ImageList<T extends Cars | Planes> = {
[key in T]: string;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.