我想迭代一个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"
}
当前回答
这里发现的另一个有趣的解决方案是使用ES6 Map:
export enum Type {
low,
mid,
high
}
export const TypeLabel = new Map<number, string>([
[Type.low, 'Low Season'],
[Type.mid, 'Mid Season'],
[Type.high, 'High Season']
]);
USE
console.log(TypeLabel.get(Type.low)); // Low Season
TypeLabel.forEach((label, value) => {
console.log(label, value);
});
// Low Season 0
// Mid Season 1
// High Season 2
其他回答
具有数字enum:
enum MyNumericEnum {
First = 1,
Second = 2
}
你需要先把它转换成数组:
const values = Object.values(MyNumericEnum);
// ['First', 'Second', 1, 2]
如您所见,它同时包含键和值。钥匙先放。
之后,你可以检索它的键:
values.slice(0, values.length / 2);
// ['First', 'Second']
和值:
values.slice(values.length / 2);
// [1, 2]
对于字符串enum,你可以使用Object.keys(MyStringEnum)来分别获取key和Object.values(MyStringEnum)来分别获取值。
尽管提取混合枚举的键和值有点挑战性。
我写了一个helper函数来枚举一个枚举:
static getEnumValues<T extends number>(enumType: {}): T[] {
const values: T[] = [];
const keys = Object.keys(enumType);
for (const key of keys.slice(0, keys.length / 2)) {
values.push(<T>+key);
}
return values;
}
用法:
for (const enumValue of getEnumValues<myEnum>(myEnum)) {
// do the thing
}
该函数返回可以轻松枚举的内容,并将其转换为枚举类型。
这对于基于键值的enum更有效:
enum yourEnum {
["First Key"] = "firstWordValue",
["Second Key"] = "secondWordValue"
}
Object.keys(yourEnum)[Object.values(yourEnum).findIndex(x => x === yourValue)]
// Result for passing values as yourValue
// FirstKey
// SecondKey
让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();
如果你只搜索名称,然后迭代使用:
Object.keys(myEnum).map(key => myEnum[key]).filter(value => typeof value === 'string') as string[];