簡體   English   中英

如何將 TypeScript 枚舉鍵轉換為值和值到鍵

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

問題

  • switch 語句需要維護開銷
  • getFruit() function:
    • 接受任何不表示為可接受string值聯合的字符串(如果使用"apple""banana""orange""pear"以外的任何內容,打字稿將不會引發編譯錯誤。)我知道我可以使用絕對字符串的聯合作為type ,但開銷更大。
    • 需要提供default情況並返回默認結果。

問題

有沒有更優雅的方式來完成上述操作? 也許使用type / typeof / keyof或任何其他操作?

理想情況下,我希望能夠:

  • 完全消除 switch 語句 - (因此沒有維護開銷)
  • 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 FruitsFruit進行管理。 如果我能弄清楚如何以編程方式創建字符串文字聯合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.

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