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

如何重定义Axios实例泛型,适配RTK Query调用风格?

重定义Axios实例泛型为双参数形式

问题背景

现有配置了请求/响应拦截器的Axios实例$api,当前调用POST请求需传入重复的<ResponseType, ResponseType, RequestType>三个泛型参数,希望简化为类似RTK Query的<ResponseType, RequestType>双参数形式。

解决方案

通过TypeScript类型别名覆盖原Axios实例的post方法类型,实现双泛型约束:

  1. 定义自定义双泛型Post类型
import type { AxiosInstance, AxiosResponse, AxiosRequestConfig } from 'axios';

// 定义双泛型Post方法:第一个泛型为响应数据类型,第二个为请求体类型
type DualGenericPost = <ResponseType, RequestType>(
  url: string,
  data?: RequestType,
  config?: AxiosRequestConfig<RequestType>
) => Promise<AxiosResponse<ResponseType>>;

// 重新定义Api实例类型,替换原post方法的泛型
type ApiInstance = Omit<AxiosInstance, 'post'> & {
  post: DualGenericPost;
};
  1. 适配现有Axios实例
    将已配置好拦截器的Axios实例断言为新的ApiInstance类型:
// 假设originalApi是你已配置好拦截器的原始Axios实例
const $api: ApiInstance = originalApi;

或者直接在创建实例时指定类型:

import axios from 'axios';

const $api = axios.create({
  // 你的baseURL、超时等配置
}) as ApiInstance;

// 添加请求/响应拦截器
$api.interceptors.request.use(
  config => config,
  error => Promise.reject(error)
);

$api.interceptors.response.use(
  response => response,
  error => Promise.reject(error)
);
  1. 简化后的调用方式
    现在调用POST请求只需传入两个泛型参数,无需重复指定响应类型:
// 示例:响应类型为用户信息,请求体为创建用户的参数
$api.post<
  { id: number; name: string; email: string },
  { name: string; email: string }
>('/users', { name: 'Matvey', email: 'example@test.com' })
.then(res => {
  // res.data自动推导为{ id: number; name: string; email: string }类型
  console.log(res.data.id);
});

适配响应拦截器的特殊场景

如果你的响应拦截器直接返回response.data(而非完整的AxiosResponse),可以调整DualGenericPost的返回类型,让调用更贴近RTK Query:

type DualGenericPost = <ResponseType, RequestType>(
  url: string,
  data?: RequestType,
  config?: AxiosRequestConfig<RequestType>
) => Promise<ResponseType>;

此时调用时直接获取响应数据:

$api.post<{ id: number }, { name: string }>('/users', { name: 'Matvey' })
.then(user => {
  console.log(user.id); // 直接访问响应数据,无需res.data
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 18:50:59