vue3+ts项目中api接口的返回参数通过TS类型声明强校验

简介:vue3+ts项目中api接口的返回参数通过TS类型声明强校验

  • ts中加入了类型声明和类型强校验

    • 我们可以在项目中根目录新建文件夹types,在里面新建文件命名为api.d.ts ,在里面规范接口返回的参数类型,有利于后期维护项目,具体代码参考如下:
      	/**
        	 * 接口返回基本数据类型
        	 * <T>泛型是通过接口返回的
        	 */
        	export interface IApiBase<T>{
              
              
        	    code:number;
        	    msg:string;
        	    data:T;
        	}
      
      • 在响应拦截器里需要对返回的数据进行设置,需要引入types文件,代码如下:
        export const useApi = async<T = any> (
          request: FetchRequest,
          options?: FetchOptions<'json'>
        ) => {
                  
                  
          return await _useApi<IApiBase<T>>(request, options);
        };
        
      • 在api文件中可以这样使用
      • 入参进行了字段类型声明
      • 如不清楚后端返回的数据格式,可以设置null格式
        	/**
          	 * 注册接口
          	 * @param options code:验证码,phone:手机号
          	 */
          	
          	export const register = async(options:{
                   
                    code:string,phone:string}) => {
                  
                  
          	    return await useApi<null>('/api/user/v1/register',{
                  
                  
          	        method:'post',
          	        body:{
                  
                   code:options.code,phone:options.phone}
          	    })
          	}
        
  • 提高开发效率插件-Paste JSON as Code

    • 将定义好的接口协议 json 参数快速转成TS interface代码

    • 使用指令

      mac:command+shift+p
      windows:ctrl+shift+p
      

      在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/u011313034/article/details/131111963