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

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

当前回答

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

其他回答

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

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

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

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

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

虽然答案已经提供了,但几乎没有人指向文档

下面是一个片段

enum Enum {
    A
}
let nameOfA = Enum[Enum.A]; // "A"

请记住,string enum成员根本不会生成反向映射。

我发现这个解决方案更优雅:

for (let val in myEnum ) {

 if ( isNaN( parseInt( val )) )
     console.log( val );
}

它显示:

bar 
foo

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