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,
  });
}
相關文章
相關標籤/搜索