How to merge Enums in TypeScript

How to merge Enums in TypeScript

Use the spread syntax to merge the enums into an object. Get the type of the object. Use bracket notation to access members of both enums on the type.

Merging String Enums in TypeScript

To merge enums in TypeScript:

  1. Use the spread syntax to merge the enums into an object.
  2. Get the type of the object.
  3. Use bracket notation to access members of both enums on the type.
// ✅ For STRING Enums
enum Sizes1 {
  Small = 'S',
  Medium = 'M',
}

enum Sizes2 {
  Large = 'L',
  ExtraLarge = 'XL',
}

export const Sizes = { ...Sizes1, ...Sizes2 };

// 👇️ {Small: 'S', Medium: 'M', Large: 'L', ExtraLarge: 'XL'}
console.log(Sizes);

export type Sizes = typeof Sizes;

// ✅ Now you can access the properties of both enums
type XL = Sizes['ExtraLarge'];
type S = Sizes['Small'];

Enums in TypeScript are real objects and exist at runtime, so we are able to use the spread syntax (...) to merge 2 enums into an object.

If your Enums have duplicate keys, the latter value wins

All of the rules for merging objects apply - if a key is present in both enums, the value of the latter is contained in the final object.

We used the typeof operator to get the type of the object and can now use bracket notation to access the members of both enums.

Merging Numeric Enums in TypeScript

When working with numeric enums, you should provide an initial value for the enums, so you don't get multiple different enum keys that point to the same value.

// ✅ For Numeric Enums
enum Sizes1 {
  Small = 0,
  Medium,
}

enum Sizes2 {
  Large = 2,
  ExtraLarge,
}

export const Sizes = { ...Sizes1, ...Sizes2 };

// 👇️ {Small: 'S', Medium: 'M', Large: 'L', ExtraLarge: 'XL'}
console.log(Sizes);

export type Sizes = typeof Sizes;

type XL = Sizes['ExtraLarge'];
type S = Sizes['Small'];

The first enum has an initial value of 0, and the second 2. This way we don't get a clash of multiple keys pointing to the same values.

Note that the examples above would not work if you use const enums, because const enums can only use constant enum expressions and are completely removed during compilation.

# Details

Published on March 11, 2024 2 min read

Typescript