The return parameters of the api interface in the vue3+ts project pass the strong verification of the TS type declaration

Introduction: The return parameters of the api interface in the vue3+ts project are strongly verified through the TS type declaration

  • Type declaration and type strong verification are added to ts

    • We can create a new folder types in the root directory of the project, and create a new file named api.d.ts in it, and standardize the parameter types returned by the interface in it, which is conducive to later maintenance projects. The specific code reference is as follows:
      	/**
        	 * 接口返回基本数据类型
        	 * <T>泛型是通过接口返回的
        	 */
        	export interface IApiBase<T>{
              
              
        	    code:number;
        	    msg:string;
        	    data:T;
        	}
      
      • In the response interceptor, you need to set the returned data, and you need to import the types file. The code is as follows:
        export const useApi = async<T = any> (
          request: FetchRequest,
          options?: FetchOptions<'json'>
        ) => {
                  
                  
          return await _useApi<IApiBase<T>>(request, options);
        };
        
      • It can be used like this in the api file
      • The input parameter has a field type declaration
      • If you do not know the data format returned by the backend, you can set the null format
        	/**
          	 * 注册接口
          	 * @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}
          	    })
          	}
        
  • Improve development efficiency plugin-Paste JSON as Code

    • Quickly convert the defined interface protocol json parameters into TS interface code

    • use instructions

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

      insert image description here

Guess you like

Origin blog.csdn.net/u011313034/article/details/131111963
Recommended