【问题标题】:Merge TypeScript enums into one [duplicate]将 TypeScript 枚举合并为一个 [重复]
【发布时间】:2021-10-10 16:49:50
【问题描述】:

为方便起见,我想合并两个单独的枚举。

export enum ActionTypes1 {
  ClearError = 'CLEAR_ERROR',
  PrependError = 'PREPEND_ERROR',
}

export enum ActionTypes2 {
  IncrementCounter = 'INCREMENT_COUNTER',
}

是否可以调用一个枚举来访问两者的数据?

例如

Foo.ClearError // works
Foo.IncrementCounter // works

对于上下文,我使用枚举作为函数名称。在这里用一个常量替换枚举:

// Error: A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.

async [ActionTypes.IncrementCounter]({ commit }) { 

【问题讨论】:

标签: typescript


【解决方案1】:

您可以创建一个const 对象来完成相同的操作:

const Foo = {
  ...ActionTypes1,
  ...ActionTypes2
} as const;
type Foo = ActionTypes1 | ActionTypes2

const bar: ActionTypes1 = Foo.ClearError;
const baz: Foo = ActionTypes2.IncrementCounter;

【讨论】:

  • 这里的'type Foo'的目的是什么? TypeScript 说它覆盖了第一行。
  • 没有Foo,你不能做const f: Foo = ...。请参阅编辑的示例。此外,我没有看到它在 playground 中被覆盖。
  • 我认为这是我严格的 eslint 规则的副作用,抛出:[eslint @typescript-eslint/no-redeclare] [E] 'Foo' is already defined。
猜你喜欢
  • 1970-01-01
  • 2018-07-06
  • 2021-10-21
  • 2014-05-31
  • 1970-01-01
  • 2020-09-18
  • 2017-12-08
  • 2021-02-09
  • 2020-08-10
相关资源
最近更新 更多