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