如何在Typescript中将字符串转换为枚举类型

24

枚举定义:

enum Colors {
  Red = "red",
  Blue = "blue"
}

如何将任意字符串(例如来自GET请求的结果)转换为枚举?

const color: Colors = "blue"; // Gives an error

此外,为什么整数枚举可以工作,但字符串枚举无法具有相同的行为?

enum Colors {
  Red = 1,
  Blue
}

const color: Colors = 1; // Works

那篇帖子上被接受的答案是矛盾的。第一种方法告诉你如何使用键访问枚举值,这不是我要求的。第二种方法似乎可行。 - Dylan Kerler
1个回答

34
如果你确定字符串始终对应于枚举中的一个项目,那么进行强制转换应该是可以的:
enum Colors {
  Red = "red",
  Blue = "blue",
}

const color: Colors = <Colors> "blue";

它无法捕获字符串无效的情况。您必须在运行时执行检查:

let colorName: string = "blue"; // from somewhere else
let color: Colors;
if (Object.values(Colors).some((col: string) => col === colorName))
  color = <Colors> colorName;
else
  // throw Exception or set default...

2
谢谢。为什么整数枚举可以直接使用,但字符串枚举除非将其转换为类型,否则无法使用? - Dylan Kerler
1
我现在无法进行测试,但我非常确定in运算符将检查枚举的键而不是值。在这个例子中,"blue"会抛出异常,但"Blue"会通过。基于数字的枚举生成一个反向映射,但基于字符串的枚举则不会。 - Daniel
5
出现了一个问题,使用这种类型的转换时,我一直收到错误提示:“JSX元素'Colors'没有对应的闭合标签”,所以我必须以不同的方式进行转换才能使其正常工作:color = colorName as Colors。 - Pepe Alvarez
在上面的代码中,将 .some(... 更改为 .find(...,这样它就会在找到正确的枚举值后停止迭代。 - user358041

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接