10
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

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

3 Comments

You can also validate the number by indexing it through the enum type twice: const enumValue: SomeEnum | undefined = SomeEnum[SomeEnum[n] as keyof typeof SomeEnum]
@E_net4theflagger nice approach!
It's no longer possible to assign it in TypeScript 5.0 (which is in beta now) – tsplay.dev/Wzaz4m