如何在打字稿2.9.1中将字符串转换为枚举?

时间:2018-09-27 02:03:55

标签: typescript

我有一个这样的枚举定义:

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的方法来做到这一点?

1 个答案:

答案 0 :(得分:0)

在TS 2.9.1中,可以通过如下定义参数类型来解决:

const key: ConfirmActionKeys.yes | ConfirmActionKeys.no | ConfirmActionKeys.cancel | ConfirmActionKeys.ok = "ok";
sayHi(key);