javascript - 检查常量 typescript 中是否存在字符串

标签 javascript typescript

我有一些像这样的常量

export class CustomerType {
  static readonly main = 'mainCustomer';
  static readonly additional = 'additionalCustomer';
}

我有

const value = 'main'

是否可以检查 CustomerType 中是否存在值并返回 true 或 false? 我知道我可以使用 include 什么时候是数组但这是类?

最佳答案

您可以使用 Object.keys()获取 class 的所有属性,然后使用 Array.prototype.includes()查看它是否包含:

class CustomerType {
  static readonly main = 'mainCustomer';
  static readonly additional = 'additionalCustomer';
}

const value = 'main'


console.log(Object.keys(CustomerType).includes(value))

您可以在 the typescript playground 中看到这个工作.

关于javascript - 检查常量 typescript 中是否存在字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70973762/

相关文章:

typescript - 类型不可分配给类型 2322

Javascript - 格式化数字以始终显示原始小数位

带有 Express : Type 'typeof import("express")' has no call signatures 的 TypeScript

css - 如何在 Ionic 2+ 中自动换行 ionic 输入?

c# - 谁可以在 C# 中为 dankogai 的 javascript deflate 实现 inflate?

Angular 2引用@ContentChild的动态实例

node.js - 如何禁用 TypeScript Object.defineProperty(exports, "__esModule", { value : true })?

javascript - 无法在 Angular JS 中删除 cookie

javascript - 对象.申请(对象): is it safe and performant?

javascript - 逗号分隔的数字正则表达式 - 接受管道字符