Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript function to convert string enum member to enum

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?

like image 662
sir_thursday Avatar asked Jan 25 '18 19:01

sir_thursday


1 Answers

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');
like image 82
Fenton Avatar answered Sep 18 '22 01:09

Fenton