【问题标题】:typescript string enum, reverse mapping equivalent打字稿字符串枚举,反向映射等效
【发布时间】:2018-02-24 13:51:12
【问题描述】:

我有一个字符串枚举,需要检查文字是否与枚举有关。反向映射不适用于字符串枚举。

假设

enum Animals{
    cat="c";
    dog="d";
    fish="f";
}

let animal= "d";

animal 是 Animals 的成员吗? 考虑到枚举是一个可以迭代和检查的对象:

function inEnum(what, enu):boolean{
    for (let item in enu){
        if (enu[item]==what){
            return true;
        }
    }
    return false;
}

有更好的方法吗?这种技术会在未来的版本中中断吗?

【问题讨论】:

    标签: typescript enums


    【解决方案1】:

    ts-enum-util (github, npm) 库支持使用运行时验证验证枚举名称/值和类型安全的 value->key 和 key->value 查找以及抛出错误或返回默认值。

    例子:

    import {$enum} from "ts-enum-util";
    
    enum Animals{
        cat="c";
        dog="d";
        fish="f";
    }
    
    let animal= "d"; 
    
    // true
    const isAnimal = $enum(Animals).isValue(animal);
    
    // the "isValue" method is a custom type guard
    if ($enum(Animals).isValue(animal)) {
        // type of "animal" in here is "Animals" instead of "string"
    }
    
    // type: ("cat" | "dog" | "fish")
    // value: "dog"
    const name = $enum(Animals).getKeyOrThrow(animal); 
    

    【讨论】:

      【解决方案2】:

      在直接回答问题之前,值得一提的是,TypeScript 支持Union Type,这通常比字符串enum 更适合这种类型的东西。示例:

      type Animal = 'cat' | 'dog' | 'fish';
      
      let myAnimal1: Animal = 'cat'; // ok
      let myAnimal2: Animal = 'buttercup'; // compile-time error "'buttercup' is not assignable to type Animal"
      

      这种方法的好处是在编译时让您知道某个值对于Animals 类型是否有效。


      现在,为了回答您关于在运行时间确定值是否在enum 中的问题,我们有in 运算符,我们可以使用它来重构您的inEnum 函数如下:

      let inEnum = (val, enumObj) => val in enumObj;
      
      inEnum("d", Animals) //evaluates to true
      inEnum("z", Animals) //evaluates to false
      

      甚至完全放弃函数调用,直接使用in 运算符:

      "d" in Animals //evaluates to true
      "z" in Animals //evaluates to false
      

      但是,没有任何迹象表明您自己的上述方法会在未来的版本中失效。

      【讨论】:

      • 使用 in 运算符,直接使用它而不是调用函数会更干净。谢谢!
      猜你喜欢
      • 2017-12-06
      • 2022-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-23
      相关资源
      最近更新 更多