Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert number to enum

Tags:

typescript

enum SomeEnum {
  a = 10
  b = 20
}

const n: number = 20;

const enumValue: SomeEnum = ???;

Is there a way to convert n to enumValue without having to write a switch-case for every enum-type.


1 Answers

Yes, there is a way:

enum SomeEnum {
  a = 10,
  b = 20
}

const n: number = 20;

const enumValue: SomeEnum = 20; // ok

const enumValue: SomeEnum = 21; // ok, please keep in mind it is unsafe

I encourage you to not do it.


Like @Beraliv mentioned in their comment, since TS 5.0 All enums Are Union enums, there is an error if you want to assign invalid number:

const enumValue: SomeEnum = 21;

If you can't switch to the newest version of TypeScript, you can check my article about safer enums and my answer

like image 83
captain-yossarian Avatar answered May 01 '26 09:05

captain-yossarian