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

如何在TypeScript中正确处理AxiosError以获取error.response.data.status?

正确处理AxiosError中response.data的unknown类型问题

方法1:给AxiosError指定泛型类型

直接给AxiosError传入自定义的错误响应类型,让TypeScript明确response.data的结构,避免unknown类型报错。

// 定义服务器返回的错误响应结构
interface ServerErrorResponse {
  status: string;
}

// 使用时为AxiosError指定泛型参数
(e: AxiosError<ServerErrorResponse>) => {
  console.log(e.response?.data.status); // 此时data类型为ServerErrorResponse,无类型错误
};

方法2:用类型守卫缩小类型范围

如果无法提前确定泛型,或者需要在运行时验证响应格式,写一个类型守卫函数来确保数据符合预期,再访问属性。

interface ServerErrorResponse {
  status: string;
}

// 类型守卫函数:验证数据是否符合预期结构
function isServerErrorResponse(data: unknown): data is ServerErrorResponse {
  return (
    typeof data === 'object' &&
    data !== null &&
    'status' in data &&
    typeof (data as ServerErrorResponse).status === 'string'
  );
}

// 使用时先做类型校验
(e: AxiosError) => {
  const errorData = e.response?.data;
  if (isServerErrorResponse(errorData)) {
    console.log(errorData.status); // 此处data类型已被缩小为ServerErrorResponse
  } else {
    // 处理格式不符合预期的情况
    console.log('错误响应格式不符合预期');
  }
};

方法3:全局扩展Axios错误类型

如果项目中所有错误响应都遵循同一格式,可以全局扩展Axios的类型定义,不用每次手动指定泛型。

在项目根目录创建或修改axios.d.ts文件:

import axios from 'axios';

declare module 'axios' {
  // 定义全局错误响应类型
  interface ServerErrorResponse {
    status: string;
  }

  // 扩展AxiosError,默认使用自定义错误响应类型
  interface AxiosError<T = ServerErrorResponse> extends Error {
    response?: AxiosResponse<T>;
  }
}

之后在项目中使用AxiosError时,response.data默认就是ServerErrorResponse类型,无需额外配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 04:36:22