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

如何定义Axios错误响应的TypeScript数据类型

Axios接口请求成功/错误响应的类型自动推导方案

核心实现

利用Axios自带的泛型类型定义,明确错误场景下的响应data类型,配合as const元组常量断言,就能实现解构后两个返回值的类型自动推导,不需要额外的手动类型转换。

首先从axios包导入内置的类型定义:

import type { AxiosError } from 'axios';

修改原有的GetIndustry函数,在catch块中给捕获的错误指定泛型参数:

export const GetIndustry = async () => {
    const base = Config.api_url;
    const endpoint = "/api/industry";
    const url = base + endpoint;

    try {
        const response = await HttpClient.get<IIndustryGroupList[]>(url, options);
        return [response, null] as const;
    } catch (err) {
        // 指定AxiosError的泛型参数,即可定义错误场景下response.data的类型
        const axiosErr = err as AxiosError<IAPIErrorResponse>;
        return [null, axiosErr.response] as const;
    }
};

实现原理

  • Axios内置的AxiosError<TErrorData>泛型类型,第一个类型参数就对应错误响应中data字段的类型,传入你定义的IAPIErrorResponse后,TS会自动将axiosErr.response.data推导为对应类型。
  • 返回值末尾的as const会将返回的数组标记为只读元组,TS会精准保留元组每个位置的类型,不会将其推导为宽泛的联合类型数组,因此解构时能直接拿到对应位置的正确类型。

使用方式

调用接口后通过简单的判空做类型收窄,即可获得完整的类型提示:

const [response, error] = await GetIndustry();

if (error) {
    // 此处error.data自动推导为IAPIErrorResponse类型
    console.log('请求错误', error.data);
    return;
}
// 此处response.data自动推导为IIndustryGroupList[]类型
console.log('行业列表数据', response.data);

通用封装优化

如果项目中接口较多,可以封装一个通用的请求包装函数,避免每个接口重复书写try/catch逻辑,同时保留完整的类型推导能力:

import type { AxiosResponse, AxiosError } from 'axios';

/**
 * 通用请求包装,统一返回[成功响应, 错误响应]元组
 * @template SuccessData 成功状态下response.data的类型
 * @template ErrorData 错误状态下response.data的类型,默认使用全局统一错误结构IAPIErrorResponse
 */
export const requestWrapper = async <SuccessData, ErrorData = IAPIErrorResponse>(
    req: Promise<AxiosResponse<SuccessData>>
) => {
    try {
        const res = await req;
        return [res, null] as const;
    } catch (err) {
        const error = err as AxiosError<ErrorData>;
        return [null, error.response] as const;
    }
};

// 后续定义接口可以简化为
export const GetIndustry = async () => {
    const url = `${Config.api_url}/api/industry`;
    return requestWrapper<IIndustryGroupList[]>(HttpClient.get(url, options));
};

如果某个接口返回特殊的错误结构,只需要传入第二个泛型参数即可自定义错误类型,适配性更强。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 15:18:19