typescript - 如何遍历 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)
我该如何解决?
解决方案
您需要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.
}
推荐阅读
- javascript - 如何将变量从 JavaScript 输出到 HTML
- javascript - Google 表格脚本 | 全局变量在 html 侧边栏/模态窗口后失去其价值
- opengl-es - 你能glBlitFramebuffer在同一纹理的不同层次之间吗?
- bash - 如何更改我的 bash 提示符以显示我以前的工作目录?
- xcode - SwiftUI - 我们如何重新绑定绑定的可选参数?
- amazon-web-services - Rails 5 - AWS Secrets Manager
- java - 当我尝试通过架构使用 DocumentBuilderFactory 验证 xml 文件时,我收到错误“找不到元素的声明”
- css - 溢出滚动隐藏但不是内容
- python - 在子任务中创建的异步子进程,任务始终挂起
- python - 如何在 Flask 中打开和处理 .rtf 文件