我想迭代一个TypeScript枚举对象,并获得每个枚举符号名称,例如: enum myEnum {entry1, entry2}
for (var entry in myEnum) {
// use entry's name here, e.g., "entry1"
}
我想迭代一个TypeScript枚举对象,并获得每个枚举符号名称,例如: enum myEnum {entry1, entry2}
for (var entry in myEnum) {
// use entry's name here, e.g., "entry1"
}
当前回答
让ts-enum-util (github, npm)为您工作,并提供许多额外的类型安全实用程序。适用于字符串和数字enum,正确忽略数字enum的数字索引反向查找条目:
字符串枚举:
import {$enum} from "ts-enum-util";
enum Option {
OPTION1 = 'this is option 1',
OPTION2 = 'this is option 2'
}
// type: ("OPTION1" | "OPTION2")[]
// value: ["OPTION1", "OPTION2"]
const keys= $enum(Option).getKeys();
// type: Option[]
// value: ["this is option 1", "this is option 2"]
const values = $enum(Option).getValues();
数字枚举:
enum Option {
OPTION1,
OPTION2
}
// type: ("OPTION1" | "OPTION2")[]
// value: ["OPTION1", "OPTION2"]
const keys= $enum(Option).getKeys();
// type: Option[]
// value: [0, 1]
const values = $enum(Option).getValues();
其他回答
要获得枚举值的列表,您必须使用:
enum AnimalEnum {
DOG = "dog",
CAT = "cat",
MOUSE = "mouse"
}
Object.values(AnimalEnum);
这不是你问题的确切答案,但它是解决你问题的一个技巧。
export module Gender {
export enum Type {
Female = 1,
Male = 2
};
export const List = Object.freeze([
Type[Type.Female] ,
Type[Type.Male]
]);
}
您可以以自己想要的方式扩展列表模型。
export const List = Object.freeze([
{ name: Type[Type.Female], value: Type.Female } ,
{ name: Type[Type.Male], value: Type.Male }
]);
现在,你可以这样使用它:
for(const gender of Gender.List){
console.log(gender.name);
console.log(gender.value);
}
or:
if(i === Gender.Type.Male){
console.log("I am a man.");
}
当我遇到同样的问题时,你可以使用我写的enum-values包:
Git: enum-values
var names = EnumValues.getNames(myEnum);
你可以用下面的方法从Enum中获取一个名称数组:
const enumNames: string[] = Object.keys(YourEnum).filter(key => isNaN(Number(key)));
老问题了,为什么不使用const对象映射呢?
不要这样做:
enum Foo {
BAR = 60,
EVERYTHING_IS_TERRIBLE = 80
}
console.log(Object.keys(Foo))
// -> ["60", "80", "BAR", "EVERYTHING_IS_TERRIBLE"]
console.log(Object.values(Foo))
// -> ["BAR", "EVERYTHING_IS_TERRIBLE", 60, 80]
这样做(注意as const强制转换):
const Foo = {
BAR: 60,
EVERYTHING_IS_TERRIBLE: 80
} as const
console.log(Object.keys(Foo))
// -> ["BAR", "EVERYTHING_IS_TERRIBLE"]
console.log(Object.values(Foo))
// -> [60, 80]