Last updated: Feb 26, 2024
Reading timeยท2 min
To merge enums in TypeScript:
// โ 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.
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.
// โ 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.
You can learn more about the related topics by checking out the following tutorials: