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

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

当前回答

具有数字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)来分别获取值。

尽管提取混合枚举的键和值有点挑战性。

其他回答

根据TypeScript文档,我们可以通过Enum和静态函数来实现这一点。

使用静态函数获取Enum名称

enum myEnum { 
    entry1, 
    entry2 
}

namespace myEnum {
    export function GetmyEnumName(m: myEnum) {
      return myEnum[m];
    }
}


now we can call it like below
myEnum.GetmyEnumName(myEnum.entry1);
// result entry1 

要阅读更多关于Enum的静态函数,请点击下面的链接 https://basarat.gitbooks.io/typescript/docs/enums.html

从TypeScript 2.4开始,枚举可以包含字符串初始化器https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html

这允许你这样写:

 enum Order {
      ONE = "First",
      TWO = "Second"
 }

console.log(`One is ${Order.ONE.toString()}`);

得到这样的输出:

一个是First

对我来说,一个更简单、实用和直接的方法来理解正在发生的事情,就是下面的列举:

enum colors { red, green, blue };

本质上将转换为:

var colors = { red: 0, green: 1, blue: 2,
               [0]: "red", [1]: "green", [2]: "blue" }

正因为如此,以下情况将是正确的:

colors.red === 0
colors[colors.red] === "red"
colors["red"] === 0

这创建了一个简单的方法来获取枚举的名称,如下所示:

var color: colors = colors.red;
console.log("The color selected is " + colors[color]);

它还创建了一种将字符串转换为枚举值的好方法。

var colorName: string = "green";
var color: colors = colors.red;
if (colorName in colors) color = colors[colorName];

以上两种情况更为常见,因为通常您对特定值的名称和以通用方式序列化值更感兴趣。

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

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

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

这不是你问题的确切答案,但它是解决你问题的一个技巧。

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.");
}