当前位置:网站首页>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:
Parameters :Extract function parameter of type the type of list; NonNullable :Extract the incoming type except for null、undefined 以外的类型;
Type programming analysis:
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) => {}
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>) => {}
}
执行完 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
完整的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 也不迟 ~~~
边栏推荐
- sqlserver无法远程连接
- OSF understands the agile development model in one minute
- Euler system (euleros): upgrade Mysql
- When opening a MYSQL table, some can display editing, some do not, how to set.
- 【Make YOLO Great Again】YOLOv1-v7全系列大解析(Neck篇)
- 初出茅庐的小李第112篇博客项目笔记之机智云智能浇花器实战(1)-基础Demo实现
- Parse the bootargs from the device tree (dtb format data)
- 内核的解压缩过程详解
- MYSQL master-slave replication
- Basic usage concepts of vim
猜你喜欢
开源项目站点必备&交流区功能
【搜索专题】看完必会的BFS解决最短路问题攻略
[cellular automata] based on matlab interface aggregation cellular automata simulation [including Matlab source code 2004]
元宇宙改变人类工作模式的四种方式
Ordinary users cannot access HGFS directory
Replacing the Raspberry Pi Kernel
win10 固定本机IP
普通用户无法访问hgfs目录
《少年派2》:新男友竟脚踩两只船,林妙妙与钱三一感情回温
YOLO怎么入门?怎么实现自己的训练集?
随机推荐
LeetCode每日一练 —— 环形链表问题(面试四连问)
MYSQL transactions
Lua introductory case of actual combat 1234 custom function and the standard library function
leetcode: 1648. Color ball with decreasing sales value [Boundary find by two points]
Handwritten binary search tree and test
You need to know the TCP wave four times
Guys, MySQL cdc source recycles replication slave and r in incremental process
OSD读取SAP CRM One Order应用日志的优化方式
Compiled on unbutu with wiringPi library and run on Raspberry Pi
Ordinary users cannot access HGFS directory
软考高级系统架构设计师系列之:系统开发基础知识
STK8321 I2C (Shengjia-accelerometer) example
如何下载Keil包
元宇宙改变人类工作模式的四种方式
Completely closed Chrome updated and in the top right corner of the tip
Introduction to the decision logic of WAASAP WebClient UI page labels
[Data analysis] Based on matlab GUI student achievement management system [including Matlab source code 1981]
更换树莓派内核
设备树的树形结构到底是怎样体现的?
带你体验一次类型编程实践