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

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

当前回答

这里的答案似乎都不能在严格模式下使用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]

其他回答

这里发现的另一个有趣的解决方案是使用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 AnimalEnum {
  DOG = "dog", 
  CAT = "cat", 
  MOUSE = "mouse"
}

Object.values(AnimalEnum);

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

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

根据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

这里的答案似乎都不能在严格模式下使用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]