简体   繁体   English

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

[英]Convert string to enum with generics

How can I convert a string to Enum using generics in TypeScript? 如何在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>()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM