我找到this great answer关于如何将字符串转换为打字稿枚举 . 基于此我写了这个功能
enum Color { Red='red', Green='green' }
function mapColorString(strColor: string): Color {
const colorKey = strColor as keyof typeof Color
return Color[colorKey]
}
但现在当我试图让它变得通用时,
function getEnumFromString<T>(str: string): T {
const enumKey = str as keyof T
return T[enumKey]
}
我在return语句中得到错误: 'T' only refers to a type, but is being used as a value here.
我想使这个通用,因为我需要根据它们的字符串值生成许多枚举,并且我希望每个都没有单独的方法 .
2 回答
当我传递枚举定义时,我可以让它工作:
T
将成为枚举的类型 . 类型被擦除,并且在运行时不存在 . 您需要传入表示枚举的对象:K
将代表枚举的键,T
将是枚举值的类型