typescript - 如何在 typescript 2.9.1 中将字符串转换为枚举?
问题描述
我有一个这样的枚举定义:
export enum ConfirmActionKeys {
yes = 'yes',
no = 'no',
ok = 'ok',
cancel = 'cancel'
}
我得到一个字符串变量,它具有 ConfirmActionKeys 中每个成员的值,但我怎样才能使它成为一种类型ConfirmActionKeys
?下面是代码:
function sayHi(key: ConfirmActionKeys) {
}
const key = "ok";
sayHi(...); // how can I call sayHi method here
我试过sayHi(ConfirmActionKeys[key])
了,但它抱怨说[ts] Element implicitly has an 'any' type because index expression is not of type 'number'.
。有没有像valueOf
Java这样的方法来做到这一点?
解决方案
In TS 2.9.1, it can be solved by define the parameter type as below:
const key: ConfirmActionKeys.yes | ConfirmActionKeys.no | ConfirmActionKeys.cancel | ConfirmActionKeys.ok = "ok";
sayHi(key);
推荐阅读
- c# - 正则表达式将多个字符串与长字符串中的 StartWith 和 EndWith 字符串匹配
- angular - Cloudfront 上 Angular 应用程序的 SEO 友好路由
- android - 如何检测设备是否连接到 laravel 服务器?
- c# - 从字符串中删除脚本和链接标签
- git - 分支中的冲突
- linux - 有没有办法让机器 A 中的远程软链接重定向到“文件名”机器 B
- javascript - 轮监听器在事件发生后获取位置
- sap - SAP Cloud Platform 通过 CF CLI 部署 MTAR
- python - 将文本文件(.obj)数据写入python列表的函数用数据文件中的最后一个元素填充列表
- lotus-notes - 当文档选择不同的状态时如何显示错误。另一个是为什么复选框没有保存