我想迭代一个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"
}
当前回答
使用当前版本的TypeScript,你可以使用这些函数将Enum映射到你选择的记录。注意,不能用这些函数定义字符串值,因为它们查找值为数字的键。
enum STATES {
LOGIN,
LOGOUT,
}
export const enumToRecordWithKeys = <E extends any>(enumeration: E): E => (
Object.keys(enumeration)
.filter(key => typeof enumeration[key] === 'number')
.reduce((record, key) => ({...record, [key]: key }), {}) as E
);
export const enumToRecordWithValues = <E extends any>(enumeration: E): E => (
Object.keys(enumeration)
.filter(key => typeof enumeration[key] === 'number')
.reduce((record, key) => ({...record, [key]: enumeration[key] }), {}) as E
);
const states = enumToRecordWithKeys(STATES)
const statesWithIndex = enumToRecordWithValues(STATES)
console.log(JSON.stringify({
STATES,
states,
statesWithIndex,
}, null ,2));
// Console output:
{
"STATES": {
"0": "LOGIN",
"1": "LOGOUT",
"LOGIN": 0,
"LOGOUT": 1
},
"states": {
"LOGIN": "LOGIN",
"LOGOUT": "LOGOUT"
},
"statesWithIndex": {
"LOGIN": 0,
"LOGOUT": 1
}
}
其他回答
假设您坚持使用规则,只生成带有数值的枚举,您可以使用这段代码。这正确地处理了名称恰好是有效数字的情况
enum Color {
Red,
Green,
Blue,
"10" // wat
}
var names: string[] = [];
for(var n in Color) {
if(typeof Color[n] === 'number') names.push(n);
}
console.log(names); // ['Red', 'Green', 'Blue', '10']
这对于基于键值的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
可以是简短的:
enum AnimalEnum {
DOG = "dog",
CAT = "cat",
MOUSE = "mouse"
}
Object.keys(AnimalEnum).filter(v => typeof v == 'string' && isNaN(v))
我通过搜索“TypeScript iterate over enum keys”找到了这个问题。所以我只想给出对我来说有用的解。也许对别人也有帮助。
我的情况如下:我想在每个枚举键上迭代,然后过滤一些键,然后访问一些对象,其中键作为枚举的计算值。这就是没有TS误差的方法。
enum MyEnum = { ONE = 'ONE', TWO = 'TWO' }
const LABELS = {
[MyEnum.ONE]: 'Label one',
[MyEnum.TWO]: 'Label two'
}
// to declare type is important - otherwise TS complains on LABELS[type]
// also, if replace Object.values with Object.keys -
// - TS blames wrong types here: "string[] is not assignable to MyEnum[]"
const allKeys: Array<MyEnum> = Object.values(MyEnum)
const allowedKeys = allKeys.filter(
(type) => type !== MyEnum.ONE
)
const allowedLabels = allowedKeys.map((type) => ({
label: LABELS[type]
}))
在当前的TypeScript版本1.8.9中,我使用类型化enum:
export enum Option {
OPTION1 = <any>'this is option 1',
OPTION2 = <any>'this is option 2'
}
与结果在这个Javascript对象:
Option = {
"OPTION1": "this is option 1",
"OPTION2": "this is option 2",
"this is option 1": "OPTION1",
"this is option 2": "OPTION2"
}
所以我必须通过键和值查询,只返回值:
let optionNames: Array<any> = [];
for (let enumValue in Option) {
let optionNameLength = optionNames.length;
if (optionNameLength === 0) {
this.optionNames.push([enumValue, Option[enumValue]]);
} else {
if (this.optionNames[optionNameLength - 1][1] !== enumValue) {
this.optionNames.push([enumValue, Option[enumValue]]);
}
}
}
我在数组中收到选项键:
optionNames = [ "OPTION1", "OPTION2" ];