如何从打字稿中的字符串中获取一种枚举类型?

时间:2019-01-04 11:01:58

标签: 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代码在theSuit处给出了编译错误:Type 'string' is not assignable to type 'Suit'

打字稿版本为3.2.2

如何从字符串中获取Suit类型?

1 个答案:

答案 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];
}