I'd like to write something like this in Typescript:
export function stringToEnum<T>(enumObj: T, str: string): keyof T {
return enumObj[str];
}
and use it as follows:
enum MyEnum {
Foo
}
stringToEnum<MyEnum>(MyEnum, 'Foo');
where it would return
MyEnum.Foo
The function above works as expected... but the typings are throwing errors. For the parameter MyEnum
in stringToEnum<MyEnum>(MyEnum, 'Foo');
, Typescript complains tha:
Argument of type 'typeof MyEnum' is not assignable to parameter of type 'MyEnum'
which makes sense... unfortunately. Any ideas on how I can get around this?
You can do it all natively without having to write a function:
enum Color {
red,
green,
blue
}
// Enum to string
const redString: string = Color[Color.red];
alert(redString);
// String to enum
const str = 'red';
const redEnum: Color = Color[str];
alert(redEnum);
Or you can have some fun with it...
enum MyEnum {
Foo,
Bar
}
function stringToEnum<ET, T>(enumObj: ET, str: keyof ET): T{
return enumObj[<string>str];
}
const val = stringToEnum<typeof MyEnum, MyEnum>(MyEnum, 'Foo');
// Detects that `foo` is a typo
const val2 = stringToEnum<typeof MyEnum, MyEnum>(MyEnum, 'foo');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With