How to merge Enums in TypeScript

avatar
Borislav Hadzhiev

Last updated: Feb 26, 2024
2 min

banner

# 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.
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 the properties of both enums type XL = Sizes['ExtraLarge']; type S = Sizes['Small'];

merging string enums in typescript

The code for this article is available on GitHub

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.

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'];

merging numeric enums in typescript

The code for this article is available on GitHub

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev