使用泛型将字符串转换为枚举

时间:2018-09-24 11:01:15

标签: typescript typescript3.0 es2017

如何使用TypeScript中的泛型将字符串转换为Enum?

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>()

1 个答案:

答案 0 :(得分:2)

由于要将枚举的字符串名称映射到值,因此需要将实际的枚举对象发送给函数。此关系存储在枚举对象本身中。

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");