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

如何移除TypeScript异步函数catch块中的any类型?

移除catch块中的any类型解决方案

方案1:使用Axios内置AxiosError类型

Axios提供了专门的错误类型AxiosError,可以直接用来标注捕获的错误对象,同时配合类型守卫确保处理的是Axios抛出的错误:

import { AxiosError } from 'axios';

// 建议定义请求数据的具体类型,替换掉data的any
interface ApiRequestData {
  // 根据接口实际需求定义字段,比如:
  // username: string;
  // password: string;
  [key: string]: unknown; // 或者更精准的类型
}

const apiCallingFunction = async (data: ApiRequestData) => {
  try {
    const response = await axiosPost("/api", { ...data });
    return response;
  } catch (err) {
    // 类型守卫判断是否为AxiosError
    if (err instanceof AxiosError) {
      return err.response;
    }
    // 处理非Axios错误场景(如网络中断、代码逻辑错误等)
    return { status: 500, data: { message: "未知错误" } };
  }
};

方案2:自定义错误类型(适合项目有统一错误格式的场景)

如果项目有自定义的错误结构,可以自己定义错误类型并配合类型守卫使用:

// 自定义匹配Axios错误结构的类型
interface CustomApiError {
  response: {
    status: number;
    data: Record<string, unknown>;
  };
  isAxiosError: boolean;
}

const apiCallingFunction = async (data: ApiRequestData) => {
  try {
    const response = await axiosPost("/api", { ...data });
    return response;
  } catch (err) {
    // 类型守卫判断错误结构
    if (typeof err === 'object' && err !== null && 'response' in err && 'isAxiosError' in err) {
      const typedErr = err as CustomApiError;
      return typedErr.response;
    }
    return { status: 500, data: { message: "未知错误" } };
  }
};

关键注意点

  • 直接使用AxiosError是最简洁的方案,它完全匹配Axios抛出的错误结构,包含response、request、config等属性。
  • 必须添加类型守卫,因为catch块捕获的错误可能是任意类型(字符串、Error实例等),TypeScript不允许直接假设它是Axios错误。
  • 替换data: any为具体接口类型,能进一步提升代码的类型安全性,避免潜在的类型问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 12:51:08