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

TypeScript类型转换提取API嵌套数据时yarn build报错解决

报错原因

执行yarn build时会触发TypeScript严格类型校验,Object.entries()默认将遍历出的value推断为无明确属性的通用对象类型,TS无法识别你访问的myProperty1等自定义嵌套属性;开发环境通常未开启全量严格校验,因此逻辑可以正常运行。

解决方案

方案1:定义接口类型(推荐,类型安全)

先根据接口返回的结构定义对应TypeScript类型,请求时传入泛型让TS自动推导数据结构,从根源解决类型识别问题:

// 定义最内层嵌套属性类型
interface MyProperty1 {
  subProperty1: any[]; // 可替换为数组实际元素类型
  subProperty2: Record<string, any>;
}
// 定义每个键对应的value结构
interface ResultValue {
  property1?: boolean;
  myProperty1: MyProperty1;
  myProperty2: Record<string, any>;
}
// 定义接口返回的整体结构
type ApiResult = Record<string, ResultValue>;

// 请求时传入泛型,指定返回值类型
const result = await HTTPService.get<ApiResult>(`myEndpoint/v1`);
for (const [key, value] of Object.entries(result)) {
  const name = key;
  if (value.property1) {
    // TS可正确识别所有嵌套属性,无类型报错
    const myVar = value.myProperty1.subProperty1;
  }
}

方案2:遍历阶段做类型断言(快速修复)

如果暂时不需要全量类型定义,可以在遍历Object.entries结果时直接做类型断言,指定value的结构:

const result = await HTTPService.get(`myEndpoint/v1`);
// 遍历时断言entries的结构为 [字符串键, 对应结构的value] 数组
for (const [key, value] of Object.entries(result) as [string, {
  property1?: boolean;
  myProperty1: { subProperty1: any[] }
}][]) {
  const name = key;
  if (value.property1) {
    const myVar = value.myProperty1.subProperty1;
  }
}

注意:不推荐直接使用any跳过全量类型校验,明确的类型定义可以提前发现属性拼写错误、空值访问等潜在运行时问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 06:36:37