How to merge 2 Enums in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 14, 2022

banner

Photo from Unsplash

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.