簡體   English   中英

如何從打字稿中的字符串中獲取一種枚舉類型?

[英]How to get a type of enum from the string in 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處給出編譯錯誤: theSuit Type 'string' is not assignable to type 'Suit'

打字稿版本是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];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM