如何使用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>()
答案 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");