[axios, TS] 请求参数和响应体的类型声明

489 阅读1分钟

提供一种简单直接的方式给axios接口声明类型,能充分获得类型提示帮助。

// 约定:所有接口返回格式,传入data类型以覆盖默认any
export interface ApiResponse<T = any> {
  status: string;
  message: string;
  data: T;
}

import request, { type ApiResponse } from '@/utils/request';
// 说明:request只是封装过的axios实例

// 下面是一个示例接口,分别声明了请求参数和响应体的类型
export const getVideo = (data: { current: number; pageSize: number }) => {
  return request<
    void,
    ApiResponse<{ records: { id: string; title: string; publishDate: string; coverUrl: string; videoUrl: string }[] }>
  >({
    method: 'post',
    url: `/teacher_hall/get_video`,
    data
  });
};
// 说明:void只是用于类型占位,原因是我响应拦截器是 return response.data;
//      具体可以看:https://github.com/axios/axios/issues/1510#issuecomment-433775113

// 调用时,写参数会有类型提示,写 res. 时也会有响应体的类型提示
getVideo({ current: 1, pageSize: 10 }).then((res) => {
  console.log('res: ', res);
});

第一次写文章,欢迎交流。
今后会分享开发过程中的解决方案和想法。