0

How can I convert a string to Enum using generics in TypeScript?

export function getMethodEnum<T>(actionStr: string): T
{
    return actionStr as T; // does not work
}

export enum ActionEnum {
    Unknown = 0,
    Sleep = 1,
    Run
}

let action: ActionEnum = getMethodEnum<ActionEnum>()
2
  • Who is methodStr inside getMethodEnum? Commented Sep 24, 2018 at 11:03
  • @TitianCernicova-Dragomir fixed sorry. Commented Sep 24, 2018 at 11:07

1 Answer 1

2

You need to send the actual enum object to the function, since you want to map the string name of the enum to the value. This relation is stores in the enum object itself.

function getMethodEnum<T>(enumObject: T, actionStr: string): T[keyof T]
{
    return enumObject[actionStr as keyof T];
}

enum ActionEnum {
    Unknown = 0,
    Sleep = 1,
    Run
}

let action: ActionEnum = getMethodEnum(ActionEnum, "Sleep");
Sign up to request clarification or add additional context in comments.

5 Comments

Can be improved a bit by restricting actionStr to be keyof T. Playground
@AlekseyL. You are right, it's good you point it out, I thought about including that option, but OP seems to want to convert a random string to a enum.
Yeah, you're right. For random string conversion there's no point in such restriction
@TitianCernicova-Dragomir you are a life saver! Not used for this but your code inspired me for another purpose
@GôTô Happy to help :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.