将字符串转换为typescript枚举的通用函数

30 浏览
0 Comments

将字符串转换为typescript枚举的通用函数

我发现了一个关于如何将字符串转换为typescript枚举的很棒的答案,链接为:https://stackoverflow.com/a/42623905/2517147。根据这个答案,我编写了以下的函数:

enum Color { Red='red', Green='green' }
function mapColorString(strColor: string): Color {
  const colorKey = strColor as keyof typeof Color
  return Color[colorKey]
}

但是,当我试图将其泛型化时,

function getEnumFromString(str: string): T {
  const enumKey = str as keyof T
  return T[enumKey]
}

就会在返回的声明处出现错误:\'T\' only refers to a type, but is being used as a value here.

我想将它泛型化,因为我有许多需要根据它们的字符串值来生成的枚举,我不想为每个枚举都单独编写一个方法。

admin 更改状态以发布 2023年5月23日
0
0 Comments

T只是枚举类型。类型会被消除,不存在于运行时。您需要传递表示枚举的对象:

enum Color { Red='red', Green='green' }
function getEnumFromString(enumObj: { [P in K]: T },str: string): T {
    const enumKey = str as K
    return enumObj[enumKey]
}
getEnumFromString(Color, 'Red');

K将表示枚举的键,T将是枚举值的类型

0
0 Comments

当我传递枚举定义时,我可以让它起作用:

enum Color { Red='red', Green='green' }
function getEnumFromString(type: T, str: string): T[keyof T] {
    const casted = str as keyof T;
    return type[casted];
}
const bar = getEnumFromString(Color, 'Red');

0