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>()
wonea
  • 4,783
  • 17
  • 86
  • 139

1 Answers1

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");
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • Can be improved a bit by restricting `actionStr` to be `keyof T`. [Playground](https://www.typescriptlang.org/play/index.html#src=function%20getMethodEnum%3CT%2C%20K%20extends%20keyof%20T%3E(enumDefinition%3A%20T%2C%20actionStr%3A%20K)%3A%20T%5BK%5D%20%7B%0D%0A%20%20%20%20return%20enumDefinition%5BactionStr%5D%3B%0D%0A%7D%0D%0A%0D%0Aenum%20ActionEnum%20%7B%0D%0A%20%20%20%20Unknown%20%3D%200%2C%0D%0A%20%20%20%20Sleep%20%3D%201%2C%0D%0A%20%20%20%20Run%2C%0D%0A%7D%0D%0A%0D%0Aconst%20action%20%3D%20getMethodEnum(ActionEnum%2C%20'Run')%3B) – Aleksey L. Sep 24 '18 at 12:21
  • 1
    @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. – Titian Cernicova-Dragomir Sep 24 '18 at 12:24
  • Yeah, you're right. For random string conversion there's no point in such restriction – Aleksey L. Sep 24 '18 at 12:27
  • @TitianCernicova-Dragomir you are a life saver! Not used for this but your code inspired me for another purpose – GôTô Jan 31 '19 at 09:08
  • 1
    @GôTô Happy to help :) – Titian Cernicova-Dragomir Jan 31 '19 at 09:09