• ts+axios 定义接口返回值的类型


    项目场景:

    我尝试去定义 Promise<自定义>里的自定义的类型,希望与数据接口返回的类型一致目的是希望类型定义好之后可以不用去看文档也能知道这个接口返回的是哪些数据


    描述

    Axios 是一个基于 promise 的 HTTP 库:
    需要使用Promise< 自定义>

    公用get请求

    /**
     * 公用get请求
     * @param url       接口地址
     * @param msg       接口异常提示
     * @param headers   接口所需header配置
     */
    export const get = ({ url, msg = '接口异常', config }: IFRequestParam) => {
      axios.defaults.headers.common['Authorization'] = umbrella.getLocalStorage('user_token');
      return axios
        .get(url, config)
        .then((res) => {
          return res.data;
        })
        .catch((err) => {
          if (err.response && err.response.data.statusCode === '401) {
            // message.warn('请先登录');
            window.location.href = '/';
          } else if (!err.response || !err.response.data) {
            message.error(`API Server ${err.toString()}`);
            return;
          }
          if (err.response.status !== 200) {
            message.error(err.response.data.message || msg);
            return err.response.data;
          }
          message.error(err.response.data.message || msg);
        });
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    接口实例:

    接口:http://10.0.1.1/GetData

    参数:

    参数类型
    statusCodenumber
    messagestring
    valueArray< >
    //类型
    type ID = string;
    
    interface ResponseOriginal<T> {
      statusCode?: number;
      message?: string;
      value: T;
    }
    type Response<T> = ResponseOriginal<T> | undefined;
    //value
    interface Value{
      item1: {name:string | null,num:number};
      item2: ArrayValueItem3 [];
      item3: any[];  //或any一步到位....
      }
    interface ArrayValueItem3 {
      key:number | string,
      id:string,
      label:string
    }
    
    //接口
    export const GetData = (
      id: ID
    ): Promise<Response<Value>> =>   //或Promise>不过这样未知value里面的数据
      get({
        url: `${http://10.0.1.1}/GetData`,
        config: { params: { id } },
      });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    ts+axios案例

  • 相关阅读:
    Redis(五)
    【走方格的方案数】
    黑马JVM总结(八)
    Android案例手册 - 实现下多个按钮展开收缩动画工具类
    Unity 2D 游戏学习笔记(3)
    智能监控如何最大化保障生产工人权益,助力电焊车间智能化?
    Flutter:WebSocket封装-实现心跳、重连机制
    Spring Boot 使用Docker构建运行
    LeetCode 695. 岛屿的最大面积
    1. Pytorch的基本语法
  • 原文地址:https://blog.csdn.net/Z_Wonderful/article/details/127862667