如何从typescript中的字符串获取枚举类型?
我有一个枚举:如何从typescript中的字符串获取枚举类型?,typescript,Typescript,我有一个枚举: export enum Suit { SPADES = "SPADES", HEARTS = "HEARTS", DIAMONDS = "DIAMONDS", CLUBS = "CLUBS" } 然后当我尝试使用它时: for(let suit in Suit) { console.log(suit); console.log(typeof suit); const theSuit: Suit = Suit[suit]; } VS
export enum Suit {
SPADES = "SPADES",
HEARTS = "HEARTS",
DIAMONDS = "DIAMONDS",
CLUBS = "CLUBS"
}
然后当我尝试使用它时:
for(let suit in Suit) {
console.log(suit);
console.log(typeof suit);
const theSuit: Suit = Suit[suit];
}
VS code在处给出编译错误,Suit
表示:类型“string”不可分配给类型“Suit”
typescript版本是3.2.2
如何从字符串中获取
Suit
的类型?您可以使用类型断言告诉编译器Suit
肯定是Suit
的键
export enum Suit {
SPADES = "SPADES",
HEARTS = "HEARTS",
DIAMONDS = "DIAMONDS",
CLUBS = "CLUBS"
}
for(let suit in Suit) {
console.log(suit);
console.log(typeof suit);
const theSuit: Suit = Suit[suit as keyof typeof Suit];
}