我想迭代一个TypeScript枚举对象,并获得每个枚举符号名称,例如: enum myEnum {entry1, entry2}

for (var entry in myEnum) { 
    // use entry's name here, e.g., "entry1"
}

当前回答

在TypeScript中,一个enum在javascript中被编译成一个map(从键中获取值):

enum MyEnum {
  entry0,
  entry1,
}

console.log(MyEnum['entry0']); // 0
console.log(MyEnum['entry1']); // 1

它还创建了一个反向映射(从值中获取键):

console.log(MyEnum[0]); // 'entry0'
console.log(MyEnum[0]); // 'entry1'

所以你可以通过以下方式访问一个条目的名称:

console.log(MyEnum[MyEnum.entry0]); // 'entry0'
console.log(MyEnum[MyEnum.entry1]); // 'entry1'

但是,string enum在设计上没有反向映射(参见注释和pull request),因为这可能导致映射对象中的键和值之间的冲突。

enum MyEnum {
  entry0 = 'value0',
  entry1 = 'value1',
}

console.log(MyEnum['value0']); // undefined
console.log(MyEnum['value1']); // undefined

如果你想强制你的字符串enum编译一个反向映射(你必须确保所有的键和值都是不同的),你可以使用这个技巧:

enum MyEnum {
  entry0 = <any>'value0',
  entry1 = <any>'value1',
}

console.log(MyEnum['value0']); // 'entry0'
console.log(MyEnum['value1']); // 'entry1'
console.log(MyEnum[MyEnum.entry0]); // 'entry0'
console.log(MyEnum[MyEnum.entry1]); // 'entry1'

其他回答

如果它是你的枚举,你定义如下所示,名称和值是相同的,它会直接给你条目的名称。

enum myEnum { 
    entry1="entry1", 
    entry2="entry2"
 }

for (var entry in myEnum) { 
    // use entry's name here, e.g., "entry1"
}

我通过搜索“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]
    }))

我的Enum是这样的:

export enum UserSorting {
    SortByFullName = "Sort by FullName", 
    SortByLastname = "Sort by Lastame", 
    SortByEmail = "Sort by Email", 
    SortByRoleName = "Sort by Role", 
    SortByCreatedAt = "Sort by Creation date", 
    SortByCreatedBy = "Sort by Author", 
    SortByUpdatedAt = "Sort by Edit date", 
    SortByUpdatedBy = "Sort by Editor", 
}

这样做会返回undefined:

UserSorting[UserSorting.SortByUpdatedAt]

为了解决这个问题,我选择了另一种使用管道的方法:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'enumKey'
})
export class EnumKeyPipe implements PipeTransform {

  transform(value, args: string[] = null): any {
    let enumValue = args[0];
    var keys = Object.keys(value);
    var values = Object.values(value);
    for (var i = 0; i < keys.length; i++) {
      if (values[i] == enumValue) {
        return keys[i];
      }
    }
    return null;
    }
}

要使用它:

return this.enumKeyPipe.transform(UserSorting, [UserSorting.SortByUpdatedAt]);

这里的答案似乎都不能在严格模式下使用string-enum。

考虑enum为:

enum AnimalEnum {
  dog = "dog", cat = "cat", mouse = "mouse"
}

使用AnimalEnum["dog"]访问可能会导致如下错误:

元素隐式具有“any”类型,因为类型“any”的表达式不能用于索引类型“typeof AnimalEnum”.ts(7053)。

这种情况下的正确解,写为:

AnimalEnum["dog" as keyof typeof AnimalEnum]

你张贴的代码将工作;它将打印出枚举的所有成员,包括枚举成员的值。例如,以下代码:

enum myEnum { bar, foo }

for (var enumMember in myEnum) {
   console.log("enum member: ", enumMember);
}

将打印以下内容:

Enum member: 0
Enum member: 1
Enum member: bar
Enum member: foo

如果你只想要成员名,而不是值,你可以这样做:

for (var enumMember in myEnum) {
   var isValueProperty = Number(enumMember) >= 0
   if (isValueProperty) {
      console.log("enum member: ", myEnum[enumMember]);
   }
}

只打印出名字:

Enum member: bar  
Enum member: foo

注意:这有点依赖于实现细节:TypeScript将enum编译为JS对象,enum值是对象的成员。如果TS决定在未来以不同的方式实现它们,上述技术可能会中断。