7
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.

E_net4
  • 27,810
  • 13
  • 101
  • 139
  • Does this answer your question? [How do I convert a string to enum in TypeScript?](https://stackoverflow.com/questions/17380845/how-do-i-convert-a-string-to-enum-in-typescript) – Andreas Mar 15 '21 at 11:11

1 Answers1

7

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