首页 > 解决方案 > 如何遍历 TypeScript 枚举?

问题描述

我有下一个枚举:

export enum Suite {
  Spade = '♠',
  Heart = '♥',
  Club = '♣',
  Diamond = '♦',
}

尝试实现循环,但出现错误

  for (let suite in Suite) {
    console.log('item:', Suite[suite]);
  }

元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引类型“typeof Suite”。在“typeof Suite”类型上找不到带有“string”类型参数的索引签名。ts(7053)

截屏

我该如何解决?

标签: typescript

解决方案


您需要suite使用类型约束来缩小键的类型。您可以通过在循环之前声明它来做到这一点:

enum Suite {
  Spade = '♠',
  Heart = '♥',
  Club = '♣',
  Diamond = '♦',
}

let suite: keyof typeof Suite;
for (suite in Suite) {
    const value = Suite[suite];
    // ...
}

或使用Object.entries

for (const [key, value] of Object.entries(Suite)) {
    // key = Spade, etc.
    // value = ♠, etc.
}

操场


推荐阅读