【问题标题】:Conversion for string based enums Typescript 2.4+基于字符串的枚举转换 Typescript 2.4+
【发布时间】:2017-08-30 17:52:48
【问题描述】:

我有一个基于字符串的枚举(TypeScript 2.4+ 支持)。将字符串转换为相应枚举值的最佳方法是什么(如果存在?)。如果它不存在,则默认为一个值就可以了。

export enum Theory {
  RLJ = 'r + l = j',
  WinterIsComing = 'winter is coming',
  TyrionIsAarysSon = 'i buy it',
  YoungGriffIsReal = 'doubtfull'
}

我从以下开始,这当然行不通。

function getTheory(theoryString: string): Theory {
  let theory: Theory = Theory.RLJ;
  if (theoryString in Theory) {
    theory = theoryString as Theory;
  }

  return theory;
}

一种可行的方法是创建一个枚举值映射来命名,并进行反向查找,但似乎没有必要(或者 TypeScript 有更好的内置方法)。

【问题讨论】:

    标签: typescript enums


    【解决方案1】:

    我认为你无法实现你想要的。我能给你的最好的东西是这样的:

    function isTheSameTheory(theoryString: string, t: Theory) {
      return theoryString === t;
    }
    

    或者这个(这是不安全的):

    function toTheory(theoryString: string) {
      return theoryString as Theory;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-10
      • 2017-07-07
      • 1970-01-01
      • 2020-10-30
      • 2021-04-11
      • 2012-08-25
      • 2018-07-07
      相关资源
      最近更新 更多