[英]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.