我有一个字符串枚举,需要检查文字是否与枚举相关。反向映射不适用于字符串枚举。
假想
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;
}
有没有更好的方法?,这种技术在未来的版本中会有突破吗?
发布于 2018-02-20 12:31:17
在直接回答问题之前,值得一提的是,TypeScript支持联合类型,这通常比字符串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
但是,没有任何迹象表明您自己的方法在将来的版本中会被打破。
发布于 2018-02-24 05:51:12
ts-enum-util
(github,npm)库支持枚举名称/值和类型安全值->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);
https://stackoverflow.com/questions/48827943
复制相似问题