如何将字符串转换为 Typescript 中的枚举 [英] How can I cast a string to an enum in Typescript
问题描述
枚举定义:
enum Colors {
Red = "red",
Blue = "blue"
}
如何将一些任意的字符串(例如来自 GET 请求的结果)投射到枚举中?
How can I cast some arbitrary sting (e.g. a result from a GET request) to the enum?
const color: Colors = "blue"; // Gives an error
我知道在这里可以使用联合,但是我需要使用一个库,并且在这个库中他们使用的是枚举.所以我必须将我的字符串转换为它们的枚举类型.
I understand that a union can be used here instead, but there is a library that I need to use and in this library they are using an enum. So I have to cast my string into their enum type.
此外,为什么整数枚举可以工作,而字符串枚举却没有相同的行为?
In addition, why do integer enums work but string enums fail to have the same behavior?
enum Colors {
Red = 1,
Blue
}
const color: Colors = 1; // Works
推荐答案
如果您确定字符串将始终对应于枚举中的一个项目,那么将其强制转换应该没问题:
If you are sure that the strings will always correspond to an item in the enum, it should be alright to cast it:
enum Colors {
Red = "red",
Blue = "blue",
}
const color: Colors = <Colors> "blue";
它不会捕获字符串无效的情况.您必须在运行时进行检查:
It won't catch the cases where the string is not valid. You would have to do the check at runtime:
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...
这篇关于如何将字符串转换为 Typescript 中的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!