【问题标题】:Get the value of an enum by key without knowing the specific enum type在不知道具体枚举类型的情况下,按键获取枚举的值
【发布时间】:2020-02-25 23:20:54
【问题描述】:

我有一个由 3 个枚举组成的类型。

enum TextItem {
  BOOK = "inventory.book",
  PAGE = "inventory.page"
}

enum FoodItem {
  BURGER = "food.burger",
  LETTUCE = "food.lettuce",
}

enum DrinkItem {
  WATER = "drinks.water",
  COLA = "drinks.cola",
}

type Item = TextItem | FoodItem | DrinkItem;

const getEnumValue(item: Item) {
  // What to do here?
}

Item 类型的枚举在 getEnumValue 函数中传递。是哪个项目,我不知道。但可以确定它是Item 类型(例如DrinkItem.WATER)。

在函数getEnumValue中传递项目时,如何确定关联的字符串值?

我在想而不是我会说的项目keyof Item。但随后 Typescript 开始抱怨 item 的类型为 never。

【问题讨论】:

  • 您也可以发布您正在传递的项目吗?
  • 在 getEnumValue 函数中传递了一个 Item 类型的枚举。我不知道到底是通过了哪个项目。
  • 这可能会有所帮助:How to merge two enums in TypeScript.

标签: typescript enums


【解决方案1】:

您应该将所有枚举组合成一个对象:

const MENU: IMenu = {
  ... FoodItem,
  ... DrinkItem
};

这个对象的类型将是下一个

interface IMenu {
  [key: string]: Item;
}

并且在函数中,你会很容易地调用你需要的值:

Menu[item]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    相关资源
    最近更新 更多