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

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

当前回答

如果你只搜索名称,然后迭代使用:

Object.keys(myEnum).map(key => myEnum[key]).filter(value => typeof value === 'string') as string[];

其他回答

当我遇到同样的问题时,你可以使用我写的enum-values包:

Git: enum-values

var names = EnumValues.getNames(myEnum);

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

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

我写了一个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
}

该函数返回可以轻松枚举的内容,并将其转换为枚举类型。

老问题了,为什么不使用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]

从TypeScript 2.4开始,枚举不再包含键作为成员。来源TypeScript自述文件

需要注意的是,字符串初始化的枚举不能反向映射到原始枚举成员名。换句话说,你不能写Colors["RED"]来获得字符串"RED"。

我的解决方案:

export const getColourKey = (value: string ) => {
    let colourKey = '';
    for (const key in ColourEnum) {
        if (value === ColourEnum[key]) {
            colourKey = key;
            break;
        }
    }
    return colourKey;
};