我有一个枚举:
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代码在theSuit
处给出了编译错误:Type 'string' is not assignable to type 'Suit'
。
打字稿版本为3.2.2
如何从字符串中获取Suit
类型?
答案 0 :(得分:2)
您可以使用类型断言来告诉编译器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];
}