首页 > 解决方案 > 如何在 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'.。有没有像valueOfJava这样的方法来做到这一点?

标签: typescript

解决方案


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);

推荐阅读