如何用TypeScript格式化Axios请求Strapi API返回的数据
解决Strapi API请求时TypeScript类型不匹配问题
问题根源是你错误地将axios.get的泛型指定为T[],但Strapi的列表接口实际返回的是嵌套结构的对象——外层对象包含data字段,这个字段才是存放文章数组的对象,之前的类型声明让TypeScript误以为res.data直接就是T[]数组,所以解构时会报错“Property 'data' does not exist on type 'T[]'”。
解决步骤:
- 定义Strapi通用响应类型
先声明适配Strapi返回结构的泛型接口,明确响应的层级结构:
interface StrapiResponse<T> { data: { data: T[]; }; // 可选:如果需要处理Strapi返回的meta等其他字段,可以在这里添加 }
- 修正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
相关产品推荐
相关产品推荐

