我有一个这样的枚举定义:
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'.
。 Java中是否有类似valueOf
的方法来做到这一点?
答案 0 :(得分:0)
在TS 2.9.1中,可以通过如下定义参数类型来解决:
const key: ConfirmActionKeys.yes | ConfirmActionKeys.no | ConfirmActionKeys.cancel | ConfirmActionKeys.ok = "ok";
sayHi(key);