当前位置:网站首页>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 也不迟 ~~~
边栏推荐
- Browser download shortcut to desktop (PWA)
- Chinese version of Pylint inspection rules
- Game Security 03: A Simple Explanation of Buffer Overflow Attacks
- 787. Merge Sort
- MYSQL Classic Interview Questions
- The fledgling Xiao Li's 114th blog project notes: Wisdom cloud intelligent flower watering device combat (3) - basic Demo implementation
- Unity3D study notes 10 - texture array
- Simple vim configuration
- leetcode: 1648. Color ball with decreasing sales value [Boundary find by two points]
- July Bootcamp (Day 31) - Status Compression
猜你喜欢

【分层强化学习】HIRO:Data-Efficient Hierarchical Reinforcement Learning

ECCV2022 Workshop | Multi-Object Tracking and Segmentation in Complex Environments

Euler system (euleros): upgrade Mysql

Introduction to machine learning how to?

ARM 交叉编译

SC7A20 (Silan Micro-Accelerometer) Example

Flink 部署和提交job

Summary of MVCC
![ROS2 series of knowledge (4): understand the concept of [service]](/img/14/8de92a89d9c4b6476ac37408bc7788.png)
ROS2 series of knowledge (4): understand the concept of [service]

Solve the problem that Excel opens very slowly after installing MySQL
随机推荐
IDEA modifies the annotation font
Handwritten binary search tree and test
The device node structure is converted into a platform_device structure
Nmap manuals - the full version
sqlserver无法远程连接
leetcode: 1562. Find latest grouping of size M [simulation + endpoint record + range merge]
Four ways the Metaverse is changing the way humans work
Guys, MySQL cdc source recycles replication slave and r in incremental process
ECCV2022 Workshop | Multi-Object Tracking and Segmentation in Complex Environments
Modern Enterprise Architecture Framework 1
MYSQL two-phase commit
带wiringPi库在unbutu 编译 并且在树莓派运行
What is the meaning of JS timestamp?Know SQL will consider to add a timestamp, JS timestamp for the scene?
win10 固定本机IP
Simple vim configuration
500 miles
WebApi hits an Attribute to handle exceptions uniformly
787. 归并排序
【元胞自动机】基于matlab界面聚合元胞自动机模拟【含Matlab源码 2004期】
device node结构体转换成platform_device结构体