How to merge 2 Enums in TypeScript

avatar

Borislav Hadzhiev

Mon Feb 14 20222 min read

banner

Photo by Meiying Ng

Merge 2 Enums in TypeScript #

To merge 2 enums:

  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.
index.ts
// ✅ 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 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.

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.

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.

index.ts
// ✅ 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.