通用函数将字符串转换为打字稿枚举

扎克·波森(Zach Posten)

我找到有关如何将字符串转换为打字稿枚举的绝佳答案基于此,我编写了此功能

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.

我想使它具有通用性,因为我需要根据它们的字符串值生成许多枚举,并且我不想为每个枚举使用单独的方法。

汤姆·卡明

通过枚举定义时,可以使它起作用:

enum Color { Red='red', Green='green' }

function getEnumFromString<T>(type: T, str: string): T[keyof T] {
    const casted = str as keyof T;
    return type[casted];
}

const bar = getEnumFromString(Color, 'Red');

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章