枚举定义:
enum Colors {
Red = "red",
Blue = "blue"
}
如何将任意字符串(例如来自GET请求的结果)转换为枚举?
const color: Colors = "blue"; // Gives an error
此外,为什么整数枚举可以工作,但字符串枚举无法具有相同的行为?
enum Colors {
Red = 1,
Blue
}
const color: Colors = 1; // Works
枚举定义:
enum Colors {
Red = "red",
Blue = "blue"
}
如何将任意字符串(例如来自GET请求的结果)转换为枚举?
const color: Colors = "blue"; // Gives an error
此外,为什么整数枚举可以工作,但字符串枚举无法具有相同的行为?
enum Colors {
Red = 1,
Blue
}
const color: Colors = 1; // Works
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...
in
运算符将检查枚举的键而不是值。在这个例子中,"blue"
会抛出异常,但"Blue"
会通过。基于数字的枚举生成一个反向映射,但基于字符串的枚举则不会。 - Daniel.some(...
更改为 .find(...
,这样它就会在找到正确的枚举值后停止迭代。 - user358041