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

TypeScript如何定义值为数组的对象接口并解决索引类型报错

问题根因

触发报错的核心是两处写法错误:

  • 入参类型声明错误:你的输入样例是单个包含数组属性的对象,并非inputData类型的对象数组。函数入参写input: inputData[]时,TS会认为传入值是一组inputData结构的对象,for...in遍历拿到的key是数组下标(字符串形式的"0"/"1"等),自然无法用[0]去索引单个inputData结构,和报错信息描述完全匹配。
  • 遍历对象时缺少类型约束:原生for...in遍历对象时,TS默认将遍历到的key识别为通用string类型,无法确认该key对应的属性一定是string[]结构,就会触发隐式any的类型校验错误。
    另外直接修改入参对象会产生隐式副作用,工程上不推荐这种写法,建议构造新的输出对象返回。
正确实现

原有接口定义不需要修改,仅需调整函数的入参类型和遍历逻辑即可,参考代码:

interface InputData {
  postcode: string[]
  submitted: string[]
}

interface OutputData {
  postcode: string
  submitted: string
}

const extract = (input: InputData): OutputData => {
  const output = {} as OutputData
  for (const key in input) {
    if (Object.prototype.hasOwnProperty.call(input, key)) {
      const typedKey = key as keyof InputData
      output[typedKey] = input[typedKey][0]
    }
  }
  return output
}

// 验证
const input = {
  postcode: ['0000'],
  submitted: ['yes']
}
const res = extract(input) // res类型为OutputData,值与预期输出一致

如果实际场景需要批量处理数组形式的输入,可以调整为批量转换逻辑:

const extractBatch = (inputList: InputData[]): OutputData[] => {
  return inputList.map(input => {
    const output = {} as OutputData
    for (const key in input) {
      if (Object.prototype.hasOwnProperty.call(input, key)) {
        const typedKey = key as keyof InputData
        output[typedKey] = input[typedKey][0]
      }
    }
    return output
  })
}

编码规范提示:TS接口名推荐使用大驼峰格式(首字母大写),和类型、类的命名规则保持一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 17:18:05