如何使用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>()
您需要将实际的enum对象发送到函数,因为您要将enum的字符串名称映射到值。此关系存储在枚举对象本身中。
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");