An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
September 15, 2022 03:17 pm GMT
Original Link: https://dev.to/egorovsa/how-to-extend-enum-in-typescript-cj4
How to extend enum in TypeScript
From time to time you need to extend an enum in TypeScript, however, we can't use extends
construction like in case of interface
.
enum MySuperEnum { ONE, TWO}enum MyMoreSuperEnum extends MySuperEnum // This is wrong
Of course, we can create one more enum and then create union type:
enum MySuperEnumExtender { THREE}type MyUnionType = MySuperEnum | MySuperEnumExtender;
What we can get and why this approach is not good? MyUnionType
is a type, we can't use it like enum to call its props.
So what we can do then?
First of all, we should use another and more preferable way of enum implementation with const
. Why?
// describe an enum objectconst MySuperEnum = { ONE: 'ONE', TWO: 'TWO'} as const// create the MySuperEnum typetype MySuperEnum = typeof MySuperEnum[keyof typeof MySuperEnum];
What is as const
? Please click to find out more.
Cool! Now our MySuperEnum
is defined in a different way!
It is time to create new MyMoreSuperEnum
that will be extended with MySuperEnum
.
// describe an enum objectconst MyMoreSuperEnum = { ...MySuperEnum, THREE: 'THREE'} as const// create the MyMoreSuperEnum typetype MyMoreSuperEnum = typeof MyMoreSuperEnum[keyof typeof MyMoreSuperEnum];
Profit. Hope this trick will be useful for you.
Original Link: https://dev.to/egorovsa/how-to-extend-enum-in-typescript-cj4
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To