You need to enable JavaScript to run this app. React+TypeScript开发报错:类型缺失ABC接口要求的config、docs属性如何解决
优惠活动
大模型
产品
解决方案
定价
更多

React+TypeScript开发报错:类型缺失ABC接口要求的config、docs属性如何解决

问题排查

一共有三处错误导致TS报错:

  • 返回值类型不匹配:你声明getResult函数返回值为Promise<ABC>,但实际返回的是response.docs(文档数组),ABC类型要求必须同时包含config和docs两个顶层属性,仅返回文档数组必然缺少要求的属性。
  • 接口字段不匹配:你定义的ABC.config仅包含lang、min_search_length两个字段,但实际构造的response.config多了prebuild_index、separator两个额外字段,触发TS多余属性校验报错。
  • 数组类型定义错误:你写的docs: [{xxx}]属于元组类型,要求docs数组只能有1个元素,但你实际传入了2个文档对象,长度不符合类型要求。
修复方案

步骤1:修正ABC接口定义

根据你的业务需求调整接口字段:

export interface ABC {
  config: {
    lang: Array<string>,
    min_search_length: number,
    // 若你确实需要这两个配置字段就补充定义,不需要就删掉response里对应的配置项
    prebuild_index: boolean,
    separator: string
  },
  // 把元组改为普通数组,允许包含任意数量的文档对象
  docs: Array<{
    location?: string,
    text?: string,
    title?: string,
  }>
}

步骤2:修正函数返回逻辑

根据你的实际需求二选一即可:

场景1:需要返回完整的ABC类型对象

直接返回完整的response对象即可:

export async function getResult(): Promise<ABC>{
  const response: ABC = {
    config: {
      lang: ['en'],
      min_search_length: 3,
      prebuild_index: false,
      separator: '[\\s\\-]+',
    },
    docs: [
      {
        location: '#kjaksjh',
        text: 'random text',
        title: 'random text',
      },
      {
        location: '#cJbcmj',
        text: 'random text ',
        title: 'random text',
      },
    ],
  };
  return response;
}

场景2:只需要返回docs文档数组

修改函数的返回值类型声明即可:

export async function getResult(): Promise<ABC['docs']>{
  const response: ABC = {
    config: {
      lang: ['en'],
      min_search_length: 3,
      prebuild_index: false,
      separator: '[\\s\\-]+',
    },
    docs: [
      {
        location: '#kjaksjh',
        text: 'random text',
        title: 'random text',
      },
      {
        location: '#cJbcmj',
        text: 'random text ',
        title: 'random text',
      },
    ],
  };
  return response.docs;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 23:36:04