typescript自定义axios服务端返回数据接口

shims-axios.d.ts

import { AxiosInstance, AxiosRequestConfig, AxiosPromise } from "axios";
/**
 * 自定义扩展axios模块
 * @author Maybe
 */
declare module "axios" {
  export interface AxiosInstance {
    request<T = any, R = ReqRes.ResponseResult<T>>(
      config: AxiosRequestConfig
    ): Promise<R>;
    get<T = any, R = ReqRes.ResponseResult<T>>(
      url: string,
      config?: AxiosRequestConfig
    ): Promise<R>;
    delete<T = any, R = ReqRes.ResponseResult<T>>(
      url: string,
      config?: AxiosRequestConfig
    ): Promise<R>;
    head<T = any, R = ReqRes.ResponseResult<T>>(
      url: string,
      config?: AxiosRequestConfig
    ): Promise<R>;
    options<T = any, R = ReqRes.ResponseResult<T>>(
      url: string,
      config?: AxiosRequestConfig
    ): Promise<R>;
    post<T = any, R = ReqRes.ResponseResult<T>>(
      url: string,
      data?: any,
      config?: AxiosRequestConfig
    ): Promise<R>;
    put<T = any, R = ReqRes.ResponseResult<T>>(
      url: string,
      data?: any,
      config?: AxiosRequestConfig
    ): Promise<R>;
    patch<T = any, R = ReqRes.ResponseResult<T>>(
      url: string,
      data?: any,
      config?: AxiosRequestConfig
    ): Promise<R>;
  }
}

req-res.d.ts

namespace ReqRes {
  /**
   * 定义接口返回的固定格式
   * { code => 状态码, msg => '响应信息', data => 数据 }
   */
  export interface ResponseResult<T = any> {
    code: number;
    msg: string;
    data: T;
  }
  /**
   * 列表数据接口
   */
  export interface ListData {
    list: [];
    page: number;
    size: number;
    total: number;
  }
}

test-api.ts

import http from "@/utils/http";

export function redirect(params?: any) {
  return http.request({
    url: "/redirect",
    method: "get",
    params,
  });
}

export function list(params?: any) {
  return http.request<ReqRes.ListData>({
    url: "/list",
    method: "get",
    params,
  });
}
相关文章
相关标签/搜索