【问题标题】:Check if string exist in const typescript检查 const 打字稿中是否存在字符串
【发布时间】:2022-02-03 23:30:12
【问题描述】:

我有一些这样的常量

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

我有

const value = 'main'

是否可以检查 CustomerType 中是否存在值并返回 true 或 false? 我知道我可以使用 include when 是一个数组,但这是一个类?

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    您可以使用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 中看到此功能。

    【讨论】:

    • 还有Object.keys(CustomerType).indexOf(value) > -1
    【解决方案2】:
    type valueType = keyof typeof CustomerType
    
    const value: valueType = 'main'; // no error
    
    const value2: valueType = 'something else'; // throws typescript error
    

    在 typescript playground here 中查看示例。

    【讨论】:

    • 这是一个有趣的答案——我必须对understand how keyof typeof worked 进行一些研究。但似乎它绝对可以用作检测值是对象属性的一种手段。
    猜你喜欢
    • 1970-01-01
    • 2014-06-19
    • 2021-05-19
    • 2016-10-08
    相关资源
    最近更新 更多