当前位置:网站首页>Take you to experience a type programming practice

Take you to experience a type programming practice

2022-08-01 02:35:00 Xiaoxin

写作背景:

在看 uniapp The tutorial when see a lot of API 还是使用的 callback 的方式来接收 API 的执行结果,大量的 API Nested use will cause the callback hell phenomenon appears again,在 API Promise 化 This article mentions someAPIIs already done Promise 化,我这边用 cli Command to initialize the vite+ts The project found that can't use the corresponding Promise 化 API,So through a utility class to implement the,By the way, try to write a write TypeScript Type of programming code.

Utility class to write to prepare:

The code below I believe you had a similar idea jym Should be seen on the net,By defining a higher-order functions touniapp api 进行包装,And the higher-order functions returns in the implementation of the function is used when Promise 来接管 api Success of failure of the callback function.

export const promisify = (api) => {
 return (options, ...params) => {
  return new Promise((resolve, reject) => {
   api(Object.assign({}, options, {
    success: resolve,
    fail: reject
   }), ...params);
  });
 }
}

注:Higher-order functions said simple point is introduced into a function and return a function,Remember that returns the function hasn't perform,Met many stabilization throttling friend is forgot to perform in each group also asked why 的~

发挥TypeScriptType of power of:

TypescriptBuilt-in types tools:

  1. Parameters :Extract function parameter of type the type of list;
  2. NonNullable :Extract the incoming type except for null、undefined 以外的类型;

Type programming analysis:

  1. promisify Function of the input type constraints:The content of the input isuniapp api(函数),So use generics to constrain the type of input;
const promisify = <P extends (...args: any) => any>(api: P) => {}
  1. promisify Returned by the function of the input type constraints:The input type is actually uniapp api The implementation of the parameter type,So you need to use the built-in type tool(1)来提取,We extract type list first only can,With the actual needs, can be extended again:
type ParameterFirst<T extends (...args: any) => any> = Parameters<T>[0];

export const promisify = <P extends (...args: any) => any>(api: P) => {
    return (options: ParameterFirst<P>) => {}
}
  1. 执行完 promisify 返回的函数后 Promise The type of object constraint:Here only through a generic constraint state the type of success,The type of successful state is actually uniapp api 选项中 success 属性(回调函数)返回的类型.We need to extract to success 属性,Then again using the built-in type tool(1)To extract the callback function return type.
type ParameterSuccess<T extends (...args: any) => any> = ParameterFirst<NonNullable<Parameters<T>[0]['success']>>;

注:因为Parameters There may be a undefined 类型的情况,所以使用 NonNullable 来进行包装.

完整的promisify工具类:

/**
 *  uni.request({
 *      url: 'https://jsonplaceholder.typicode.com/todos/1',
 *      success: (res) => {
 *          console.log(res.data);
 *      }
 *  });
 *  
 *   promisify(uni.request)({ url: '' }).then(res => {
 *     // res.data
 *   }).catch(err => {
 *
 *   });
 *  
 * @param api 
 * @returns 
 */

/**
 * To extract the parameters passed in the first parameter of type
 */
type ParameterFirst<T extends (...args: any) => any> = Parameters<T>[0];
/**
 * To extract the parameters passed in the first parameter in thekey为success的参数的类型;
 * 因success类型为函数类型,So extracting againsuccessThe type of function of the first parameter parameters
 */
type ParameterSuccess<T extends (...args: any) => any> = ParameterFirst<NonNullable<Parameters<T>[0]['success']>>;

export const promisify = <P extends (...args: any) => any>(api: P) => {
    return (options: ParameterFirst<P>) => {
        return new Promise<ParameterSuccess<P>>((resolve, reject) => {
            api(
                Object.assign({}, options, {
                    success: resolve,
                    fail: reject,
                }),
            );
        });
    };
};

结语:

既然选择 TypeScript 来编写项目,As much as possible to play TypeScript 作用,At the time of frustration with any 也不迟 ~~~

原网站

版权声明
本文为[Xiaoxin]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/213/202208010231307537.html