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

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

当前回答

要获得枚举值的列表,您必须使用:

enum AnimalEnum {
  DOG = "dog", 
  CAT = "cat", 
  MOUSE = "mouse"
}

Object.values(AnimalEnum);

其他回答

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

Typescript游乐场示例

enum TransactionStatus {
  SUBMITTED = 'submitted',
  APPROVED = 'approved',
  PAID = 'paid',
  CANCELLED = 'cancelled',
  DECLINED = 'declined',
  PROCESSING = 'processing',
}


let set1 = Object.entries(TransactionStatus).filter(([,value]) => value === TransactionStatus.SUBMITTED || value === TransactionStatus.CANCELLED).map(([key,]) => {
    return key
})


let set2 = Object.entries(TransactionStatus).filter(([,value]) => value === TransactionStatus.PAID || value === TransactionStatus.APPROVED).map(([key,]) => {
    return key
})

let allKeys = Object.keys(TransactionStatus)



console.log({set1,set2,allKeys})

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

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];

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

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

你张贴的代码将工作;它将打印出枚举的所有成员,包括枚举成员的值。例如,以下代码:

enum myEnum { bar, foo }

for (var enumMember in myEnum) {
   console.log("enum member: ", enumMember);
}

将打印以下内容:

Enum member: 0
Enum member: 1
Enum member: bar
Enum member: foo

如果你只想要成员名,而不是值,你可以这样做:

for (var enumMember in myEnum) {
   var isValueProperty = Number(enumMember) >= 0
   if (isValueProperty) {
      console.log("enum member: ", myEnum[enumMember]);
   }
}

只打印出名字:

Enum member: bar  
Enum member: foo

注意:这有点依赖于实现细节:TypeScript将enum编译为JS对象,enum值是对象的成员。如果TS决定在未来以不同的方式实现它们,上述技术可能会中断。