[英]How to convert TypeScript Enum key to value and value to key
上下文可以說我有以下帶有字符串值的枚舉:
enum Fruit {
Apple = "apple",
Orange = "orange",
Banana = "banana",
Pear = "pear"
}
用戶總是輸入文字string
值( "apple"
、 "banana"
、 "orange"
、 "pear"
)讓我們從下拉列表中說以消除無效輸入的可能性 - 我需要將其轉換回類型Fruit
即類似這個:
function getFruit(fruit: string): Fruit {
switch (fruit) {
case "apple":
return Fruit.Apple
case "banana":
return Fruit.Banana
case "orange":
return Fruit.Orange
case "pear":
return Fruit.Pear
default:
// I DON'T WANT THIS!
return Fruit.Pear
}
}
問題
getFruit()
function:
string
值聯合的字符串(如果使用"apple"
、 "banana"
、 "orange"
、 "pear"
以外的任何內容,打字稿將不會引發編譯錯誤。)我知道我可以使用絕對字符串的聯合作為type
,但開銷更大。default
情況並返回默認結果。問題
有沒有更優雅的方式來完成上述操作? 也許使用type
/ typeof
/ keyof
或任何其他操作?
理想情況下,我希望能夠:
getFruit()
function 僅以編程方式獲取枚舉中包含的string
值(無需手動聲明和維護絕對字符串的聯合)。 ps 我不在乎我是否需要使用替代類型而不是enum
- 它的功能很重要!
到目前為止,我最接近解決方案的最佳嘗試是:
type Fruits = "apple" | "banana" | "orange" | "pear"
let Fruit = {
Apple = "apple",
Orange = "orange",
Banana = "banana",
Pear = "pear"
}
type Fruit = keyof typeof Fruit
function parseFruit(fruit: Fruits): Fruit {
return Object.keys(Fruit).find((key) => {
return Fruit[key as Fruit] === fruit
}) as Fruit
}
這仍然需要對字符串文字聯合type Fruits
和Fruit
進行管理。 如果我能弄清楚如何以編程方式創建字符串文字聯合type Fruits
,那么這個解決方案將是“完美的”。
您可以遍歷枚舉值並找到 Fruit
function getFruit(fruit: string): Fruit | null {
return Object.values(Fruit).find(item => item === fruit) ?? null
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.