我想迭代一个TypeScript枚举对象,并获得每个枚举符号名称,例如: enum myEnum {entry1, 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 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']

基于上面的一些回答,我提出了这个类型安全的函数签名:

export function getStringValuesFromEnum<T>(myEnum: T): (keyof T)[] {
  return Object.keys(myEnum).filter(k => typeof (myEnum as any)[k] === 'number') as any;
}

用法:

enum myEnum { entry1, entry2 };
const stringVals = getStringValuesFromEnum(myEnum);

stringVals的类型是'entry1' | 'entry2'

看看它的实际应用

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

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-values包:

Git: enum-values

var names = EnumValues.getNames(myEnum);

你可以用下面的方法从Enum中获取一个名称数组:

const enumNames: string[] = Object.keys(YourEnum).filter(key => isNaN(Number(key)));