Categories
TypeScript Answers

How to extend an enum in Typescript?

Spread the love

Sometimes, we want to extend an enum in Typescript.

In this article, we’ll look at how to extend an enum in Typescript.

How to extend an enum in Typescript?

To extend an enum in Typescript, we can combine the 2 enums into a union type.

And then we can use the spread operator to spread the enum entries into a new object.

For instance, we write

enum Color1 {
  Red = "Red",
  Green = "Green",
}

enum Color2 {
  Yellow = "Yellow",
  Blue = "Blue",
}

type Colors = Color1 | Color2;
const Colors = { ...Color2, ...Color1 };

to create the Color1 and Color2 enums.

Then we create a union type between them and assign it to Colors.

Next, we create an object by spreading Color2 and Color1 into a new object and assign it to Colors.

Conclusion

To extend an enum in Typescript, we can combine the 2 enums into a union type.

And then we can use the spread operator to spread the enum entries into a new object.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.