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

TypeScript中Axios联合类型访问属性报错问题求助

解决TypeScript中Axios联合类型访问属性的TS2339错误

问题原因

你定义的联合类型AxiosResponse | { error: AxiosError }中,AxiosResponse不存在error属性,而{ error: AxiosError }不存在data属性。TypeScript的类型检查要求:只有当联合类型的所有成员都包含某个属性时,才能直接访问该属性,否则会抛出TS2339错误。直接用request.error判断时,TS无法确定当前request属于哪个类型分支,因此不允许访问。

可行解决方案

1. 自定义类型守卫(推荐)

写一个类型守卫函数,显式告诉TypeScript如何区分两个类型分支,就能通过判断安全访问属性:

import { AxiosResponse, AxiosError } from 'axios';

// 自定义类型守卫函数
function isRequestError<T>(response: AxiosResponse<T> | { error: AxiosError }): response is { error: AxiosError } {
  return !!(response as { error: AxiosError }).error;
}

// 使用示例
const request = await axios.get('/api')
  .then(res => res)
  .catch(err => ({ error: err }));

if (isRequestError(request)) {
  // 此处request被TS确定为{ error: AxiosError }类型
  console.log(request.error.message);
} else {
  // 此处request被TS确定为AxiosResponse类型
  console.log(request.data);
}

2. 统一返回值结构(更清晰)

把成功响应也包装成统一的对象结构,让联合类型的每个分支都有明确的区分属性,简化类型判断:

import { AxiosResponse, AxiosError } from 'axios';

type ApiResult<T> = 
  | { success: true; data: T }
  | { success: false; error: AxiosError };

// 调整请求逻辑,统一返回结构
const request: ApiResult<YourDataType> = await axios.get('/api')
  .then(res => ({ success: true, data: res.data }))
  .catch(err => ({ success: false, error: err }));

// 直接通过success属性判断
if (!request.success) {
  console.log(request.error.message);
} else {
  console.log(request.data);
}

为什么不能直接用request.error判断?

因为AxiosResponse没有error属性,直接访问request.error本身就违反了TypeScript的类型规则——TS不允许访问一个类型可能不存在的属性。必须通过类型保护机制(in操作符或自定义类型守卫)让TS确定当前类型分支后,才能安全访问对应的属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 09:52:19