0

I'd like to merge two separate enums for convenience.

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

export enum ActionTypes2 {
  IncrementCounter = 'INCREMENT_COUNTER',
}

Is it possible to call one enum to access the data from both?

e.g.

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

For context I'm using the enum for function names. Replacing the enum with a constant breaks here:

// 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 }) { 
Andrew C.
  • 421
  • 5
  • 15
  • you may be looking for unions https://stackoverflow.com/a/60041791/4541045 – ti7 Aug 05 '21 at 16:53
  • 4
    Does this answer your question? [How to merge two enums in TypeScript](https://stackoverflow.com/questions/48478361/how-to-merge-two-enums-in-typescript) – Behemoth Aug 05 '21 at 16:54

1 Answers1

4

You can create a const object that accomplishes the same:

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

const bar: ActionTypes1 = Foo.ClearError;
const baz: Foo = ActionTypes2.IncrementCounter;
Connor Low
  • 5,900
  • 3
  • 31
  • 52
  • What is the purpose of 'type Foo' here? TypeScript says it's overriding the first line. – Andrew C. Aug 05 '21 at 17:04
  • Without `Foo`, you can't do `const f: Foo = ...`. See edited example. Also, I don't see it overriding in the [playground](https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBMAdgVwLZwIIGMYEsKIAqAnmMAM4CMcA3gFBxwDCANsAIZQCiUU0cAXjgByJgBkuGAEoB9LlKkB5KcIA0DOAAUowMogAmPPlEEjNUrpq4A5ACJyFytXQC+dOqEiwEKdNjwEJGTkAEy0GgCSiFg6qEgwTBDIiDDAJkLCEdZMFgCyNoQyTIoAqtaE8s5uHuDQ8FgE5PAAYhAQpvSMAHQ9-vhEpBSU6t29OP1BFCGucOzkcA2ITQDc7p51cDCDcK3tQn2Bg1RwAD6Y44fB03SLTXAAZgBc5wEDwdRCu12sHNy80MsgA). – Connor Low Aug 05 '21 at 17:04
  • 1
    I think it's a side-effect of my strict eslint rules, throwing: [eslint @typescript-eslint/no-redeclare] [E] 'Foo' is already defined. – Andrew C. Aug 05 '21 at 17:14