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

如何用TypeScript格式化Axios请求Strapi API返回的数据

解决Strapi API请求时TypeScript类型不匹配问题

问题根源是你错误地将axios.get的泛型指定为T[],但Strapi的列表接口实际返回的是嵌套结构的对象——外层对象包含data字段,这个字段才是存放文章数组的对象,之前的类型声明让TypeScript误以为res.data直接就是T[]数组,所以解构时会报错“Property 'data' does not exist on type 'T[]'”。

解决步骤:

  1. 定义Strapi通用响应类型
    先声明适配Strapi返回结构的泛型接口,明确响应的层级结构:
interface StrapiResponse<T> {
  data: {
    data: T[];
  };
  // 可选:如果需要处理Strapi返回的meta等其他字段,可以在这里添加
}
  1. 修正APIClient的getAll方法
    把axios.get的泛型改为上面定义的StrapiResponse<T>,让TypeScript正确识别响应结构,再提取嵌套的文章数组:
class APIClient<T> {
  endpoint: string;

  constructor(endpoint: string) {
    this.endpoint = endpoint;
  }

  getAll = () => {
    return axiosInstance.get<StrapiResponse<T>>(this.endpoint)
      .then(({ data }) => data.data);
  };
}

修改后,getAll方法会正确返回T[]类型的数组(此处为Article[]),同时TypeScript不会再抛出类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:33:19