Dyl*_*ler 8 javascript node.js typescript typescript-typings
枚举定义:
enum Colors {
Red = "red",
Blue = "blue"
}
Run Code Online (Sandbox Code Playgroud)
我如何将一些任意的刺(例如来自 GET 请求的结果)投射到枚举?
const color: Colors = "blue"; // Gives an error
Run Code Online (Sandbox Code Playgroud)
我知道在这里可以使用联合,但是我需要使用一个库,并且在这个库中他们使用的是枚举。所以我必须将我的字符串转换为它们的枚举类型。
另外,为什么整数枚举可以工作,而字符串枚举却没有相同的行为?
enum Colors {
Red = 1,
Blue
}
const color: Colors = 1; // Works
Run Code Online (Sandbox Code Playgroud)
JCO*_*611 10
如果您确定字符串将始终对应于枚举中的一个项目,则可以对其进行转换:
enum Colors {
Red = "red",
Blue = "blue",
}
const color: Colors = <Colors> "blue";
Run Code Online (Sandbox Code Playgroud)
它不会捕获字符串无效的情况。您必须在运行时进行检查:
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...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6887 次 |
| 最近记录: |