枚举定义:
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...
关于javascript - 如何将字符串转换为 Typescript 中的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62821682/