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

TypeScript遍历对象时如何正确给key声明类型解决ts(2345)报错

报错原因

  • Object.entries 原生类型定义返回的键是通用string类型,无法自动匹配你定义的TLocaleKey窄类型
  • TS 语法限制不允许直接在for...of循环的左值位置加类型注解

可行解决方案

方案1:调用时直接断言(改动最小)

在使用key的位置直接做类型断言即可:

export const getInitialStateByData = (initialData: TApiResponseData, fields: TFormFields) => {
  for (const [key] of Object.entries(initialData)) {
    if (!fields.includes(key as TLocaleKey)) {
      delete initialData[key]
    }
  }
  return initialData
}

方案2:整体断言Object.entries返回值

如果你希望解构出来的key天然就是TLocaleKey类型,可以直接断言entries的返回类型:

export const getInitialStateByData = (initialData: TApiResponseData, fields: TFormFields) => {
  for (const [key] of Object.entries(initialData) as Array<[TLocaleKey, unknown]>) {
    if (!fields.includes(key)) {
      delete initialData[key]
    }
  }
  return initialData
}

方案3:类型守卫(运行时安全)

如果需要在运行时也校验key的合法性,避免类型断言带来的安全隐患,可以加一层类型守卫:

// 先定义类型守卫,需要你填入所有合法TLocaleKey的枚举/数组
const ALL_VALID_LOCALE_KEYS: TLocaleKey[] = [] 
function isLocaleKey(key: string): key is TLocaleKey {
  return ALL_VALID_LOCALE_KEYS.includes(key as TLocaleKey)
}

export const getInitialStateByData = (initialData: TApiResponseData, fields: TFormFields) => {
  for (const [key] of Object.entries(initialData)) {
    if (!isLocaleKey(key) || !fields.includes(key)) {
      delete initialData[key]
    }
  }
  return initialData
}

额外优化建议

你当前的实现直接修改了入参initialData,会污染原始的API响应对象,建议先浅拷贝再操作:

export const getInitialStateByData = (initialData: TApiResponseData, fields: TFormFields) => {
  // 浅拷贝避免修改原对象
  const processedData = {...initialData}
  for (const [key] of Object.entries(processedData) as Array<[TLocaleKey, unknown]>) {
    if (!fields.includes(key)) {
      delete processedData[key]
    }
  }
  return processedData
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:15:03