【问题标题】:Check if string is inside enum检查字符串是否在枚举内
【发布时间】:2019-09-23 06:25:59
【问题描述】:

我有一些类似这样的枚举

export enum Types {
  advance = 'lolipo',
  test = 'testing',
  city = 'cityNumber'
}

我检查了枚举中是否存在值

 const description = 'advance';
 const isProperType = Object.values(Types).includes(description);

我得到的错误是这样的

“字符串”类型的参数不能分配给“类型”类型的参数。

【问题讨论】:

标签: angular typescript object include


【解决方案1】:

当一个枚举被转译成 javascript 时,会创建以下对象

export var Types;
(function (Types) {
    Types["advance"] = "lolipo";
    Types["test"] = "testing";
    Types["city"] = "cityNumber";
})(Types || (Types = {}));

基本上,它是一个带有一些键的对象。因此,您可以简单地使用以下表达式

description in Types

console.log(description in Types); 打印 true

【讨论】:

  • 我不相信description in Types 可用于字符串枚举。
  • 不管你信不信,它都有效。检查它out
  • 对不起,也许我弄错了。对于我的代码库,当我尝试在警卫中仅使用“x in Types”时,它给了我一个“不安全地使用'any'类型的表达式”的eslint错误。 Cherios!
【解决方案2】:

对我来说,.includes 似乎有问题,所以在你的类型保护中你可以回退到定期的相等检查,比如。

export enum Types {
  advance = 'lolipo',
  test = 'testing',
  city = 'cityNumber'
}

function isProperType(description: unknown): description is Types {
  for (const value of Types) {
    if (description === value) {
      return true
    }
  }
  return false
}

【讨论】:

    【解决方案3】:

    使用这样的表达式 -

    Object.values(ENUM).includes(ENUM.value)

    【讨论】:

    • 我认为重点是检查 string 是否是字符串枚举的成员。
    猜你喜欢
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 2014-08-09
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多