typescript字符串枚举,反向映射等价

时间:2018-02-16 13:33:15

标签: typescript enums

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

假设

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

let animal= "d";

动物是动物的一员吗? 考虑枚举对象,您可以迭代并检查:

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

有没有更好的方法?,这种技术可能会在未来版本中出现吗?

2 个答案:

答案 0 :(得分:2)

ts-enum-utilgithubnpm)lib支持使用运行时验证枚举名称/值和类型安全值 - >键和键值>值查找验证以及抛出错误或返回默认值的选项。

示例:

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); 

答案 1 :(得分:1)

在直接回答问题之前,值得一提的是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"

这种方法的好处是让您知道编译 -time值是否对Animals类型有效。

现在,为了回答您关于确定某个值是否在运行 -time的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

然而,没有任何迹象表明你自己的方法在未来版本中会破坏。