【问题标题】:How to create enum values as type/interface in typescript?如何在打字稿中创建枚举值作为类型/接口?
【发布时间】:2020-09-04 18:38:01
【问题描述】:

我有枚举:

enum DemoEnum {
    a = 'EnumValueA',
    b = 'EnumValueB'
}

我想从我的枚举值创建type Type = 'EnumValueA' | 'EnumValueB'

我该怎么做?

我目前的状态是“钥匙”类型:

type Type = keyof typeof DemoEnum // 'a' | 'b'

例如,我想在我的 react 道具中使用它。

type Props {
   value: 'EnumValueA' | 'EnumValueB',
}

万一使用<MyComponent value='EnumValueA'>

type Props {
   value: DemoEnum,
}

我收到一个错误Type .. is not assignable to DemoEnum

【问题讨论】:

  • 你为什么要这个?你能在需要这种类型的地方展示一些代码吗?根据用例,您可以只使用 DemoEnum 作为类型,因为它是您要查找的联合的子类型。
  • 在反应道具中(更新)。

标签: typescript enums


【解决方案1】:

通常enums 旨在保护用户不必关心他们的特定价值观。从某种意义上说,您应该能够更改实际的字符串/数字值,而不是更改其余代码。因此,在您的反应组件中使用它的传统方法如下所示:

type Props = {
    value: DemoEnum
}

<MyComponent value={DemoEnum.a} />

应该编译没有错误。


另一方面,如果您发现自己非常关心实际的字符串值 "EnumValueA""EnumValueB",您可能会考虑完全放弃 enums 并为其创建一个普通对象:

const DemoEnum = {
    a: 'EnumValueA',
    b: 'EnumValueB'
} as const;

并通过检查合成您关心的类型:

type DemoEnumObject = typeof DemoEnum;
type DemoEnum = DemoEnumObject[keyof DemoEnumObject];

type Props = {
    value: DemoEnum
}

然后将作为

<MyComponent value="EnumValueA" />

或作为

<MyComponent value={DemoEnum.a} />

Playground link

【讨论】:

    【解决方案2】:

    Template Literal Types发布后,你可以直接用它来得到你想要的:

    type Enum = `${DemoEnum}` //  "EnumValueA" | "EnumValueB"
    

    【讨论】:

      猜你喜欢
      • 2020-12-09
      • 2021-02-14
      • 2019-07-09
      • 2019-12-27
      • 2017-02-03
      • 1970-01-01
      • 2019-03-13
      • 2019-09-25
      相关资源
      最近更新 更多