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

如何在TypeScript中传递Axios方法的泛型参数?

Axios封装中TypeScript泛型透传问题

问题描述

我刚接触TypeScript,仍在学习泛型的相关知识。我有一个Client类,其中包含AxiosInstance属性,用于为每个请求附加请求头。我希望Client类拥有与AxiosInstance完全相同的get和post方法,已写出基础代码如下:

import Axios, { type AxiosInstance, type InternalAxiosRequestConfig } from 'axios';

class Client {
  constructor(){
    this.axios = Axios.create();

    // 给每个请求附加授权头(如果不存在的话)
    this.axios.interceptors.request.use((requestConfig: InternalAxiosRequestConfig) => {
      requestConfig.headers = {
        authorization: 'basic foobar',
        ...requestConfig.headers
      };

      return requestConfig;
    });
  }

  axios: AxiosInstance;

  get/*<这里该写什么?>*/(...args: Parameters<AxiosInstance['get']>) {
    return this.axios.get/*<这里该写什么?>*/(...args);
  }

  post/*<这里该写什么?>*/(...args: Parameters<AxiosInstance['post']>) {
    return this.axios.post/*<这里该写什么?>*/(...args);
  }
}

我的疑问:

  1. AxiosInstance.get()和AxiosInstance.post()确实带有泛型参数吗?
  2. 如何将Client.get()和Client.post()的泛型参数,像传递普通参数一样透传给AxiosInstance对应的方法?

解答

1. 关于Axios方法的泛型参数

你的表述完全正确。AxiosInstance的get、post等请求方法都定义了泛型参数,主要用于指定响应数据类型、AxiosResponse结构类型以及请求体数据类型(针对post这类带请求体的方法),以此获得更精准的类型推断。

2. 泛型参数透传的实现

你需要给Client类的get和post方法定义与Axios原生方法完全对齐的泛型参数,然后将这些参数直接传递给内部调用的this.axios.get/this.axios.post即可。

修改后的完整代码:

import Axios, { 
  type AxiosInstance, 
  type InternalAxiosRequestConfig, 
  type AxiosResponse, 
  type AxiosRequestConfig 
} from 'axios';

class Client {
  constructor(){
    this.axios = Axios.create();

    // 给每个请求附加授权头(如果不存在的话)
    this.axios.interceptors.request.use((requestConfig: InternalAxiosRequestConfig) => {
      requestConfig.headers = {
        authorization: 'basic foobar',
        ...requestConfig.headers
      };

      return requestConfig;
    });
  }

  axios: AxiosInstance;

  // 对齐Axios.get的泛型定义,实现透传
  get<T = any, R = AxiosResponse<T>, D = any>(
    ...args: Parameters<AxiosInstance['get']>
  ): Promise<R> {
    return this.axios.get<T, R, D>(...args);
  }

  // post方法同理
  post<T = any, R = AxiosResponse<T>, D = any>(
    ...args: Parameters<AxiosInstance['post']>
  ): Promise<R> {
    return this.axios.post<T, R, D>(...args);
  }
}

代码说明:

  • T:指定响应体数据的类型,默认值any和Axios原生行为保持一致
  • R:指定响应对象AxiosResponse的类型,默认是包含T的标准响应结构
  • D:指定请求体数据的类型(仅针对post、put这类带请求体的方法)
  • Parameters<AxiosInstance['get']>自动获取Axios get方法的参数类型,保证方法签名和原生完全一致
  • 调用内部Axios方法时,直接传入定义好的泛型参数T、R、D,实现泛型透传

使用示例:

const client = new Client();

// 指定响应数据类型为用户结构
client.get<{ id: number; name: string }>('/api/user')
  .then(res => {
    // res.data会被TypeScript自动推断为{ id: number; name: string }类型
    console.log(res.data.id);
  });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 10:20:36