You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何遍历以枚举为索引的对象?

解决TypeScript枚举键对象的遍历类型错误

首先纠正你代码里的两个笔误:

  • 枚举名拼写错误:FunnalStage → FunnelStage
  • 枚举成员大小写错误:FunnelStage.Login → FunnelStage.LOGIN(枚举定义的是大写LOGIN)

错误根源是:TypeScript中for...in遍历对象时,键的默认类型是string,但你的overall对象的索引类型是FunnelStage枚举,类型不匹配导致报错。以下是几种正确的实现方式:

方法一:断言遍历键为枚举类型

直接把遍历得到的字符串键断言为FunnelStage类型,让TypeScript认可这个索引:

enum FunnelStage {
    LOGIN
}

const overall = {
    [FunnelStage.LOGIN]: {count: 1}
}
// 修正大小写错误
overall[FunnelStage.LOGIN].count = 2

for (let funnelStage in overall) {
    console.log(overall[funnelStage as FunnelStage].count)
}

方法二:使用Object.entries并断言类型

通过Object.entries直接获取键值对,同时断言整个数组的类型,避免单独处理索引:

enum FunnelStage {
    LOGIN
}

const overall = {
    [FunnelStage.LOGIN]: {count: 1}
}
overall[FunnelStage.LOGIN].count = 2

for (const [stage, data] of Object.entries(overall) as Array<[FunnelStage, { count: number }]>) {
    console.log(data.count)
}

方法三:明确对象类型后遍历枚举键

先给overall指定Record<FunnelStage, { count: number }>类型,再把Object.keys的结果转为枚举数组遍历:

enum FunnelStage {
    LOGIN
}

// 明确对象类型
const overall: Record<FunnelStage, { count: number }> = {
    [FunnelStage.LOGIN]: {count: 1}
}
overall[FunnelStage.LOGIN].count = 2

// 将Object.keys结果断言为枚举成员数组
for (const stage of Object.keys(overall) as Array<FunnelStage>) {
    console.log(overall[stage].count)
}

内容的提问来源于stack exchange,提问作者mp3por

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 19:50:21