javascript - 如何将字符串转换为 Typescript 中的枚举

标签 javascript node.js typescript typescript-typings

枚举定义:

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/

相关文章:

javascript - 如何使用 JavaScriptCore 从 C 调用 JavaScript 函数?

javascript - Mongoose 与 Supertest 的开放连接问题

node.js - 为什么服务器会计算重复条目?

typescript - Angular2 将父服务注入(inject)子服务

javascript - 如何强制Typescript中的所有变量都声明一个类型

javascript - 动态地将媒体查询添加到页面并覆盖从应用程序端生成的 html 中的样式

javascript - 如何从给定的字符数组中查找所有单词的列表

javascript - Javascript 或 jQuery Flot 中的仪表图

node.js - 删除 API 后调用的 csrf protecteion

angular - 获取选择一个菜单的默认值