当前位置:网站首页>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 也不迟 ~~~
边栏推荐
- [Data analysis] Based on matlab GUI student achievement management system [including Matlab source code 1981]
- Game Security 03: A Simple Explanation of Buffer Overflow Attacks
- 初出茅庐的小李第113篇博客项目笔记之机智云智能浇花器实战(2)-基础Demo实现
- 【uniCloud】云对象的应用与提升
- Euler system (euleros): upgrade Mysql
- Inheritance Considerations
- The IDEA can't find or unable to load The main class or Module "*" must not contain The source root "*" The root already belongs to The Module "*"
- HCIP(15)
- win10 固定本机IP
- Simple vim configuration
猜你喜欢

Ordinary users cannot access HGFS directory

HCIP(14)

The fledgling Xiao Li's 114th blog project notes: Wisdom cloud intelligent flower watering device combat (3) - basic Demo implementation

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

【Make YOLO Great Again】YOLOv1-v7全系列大解析(Neck篇)

二舅

Beijing suddenly announced that yuan universe big news

《少年派2》:新男友竟脚踩两只船,林妙妙与钱三一感情回温

带wiringPi库在unbutu 编译 并且在树莓派运行
![ROS2 series of knowledge (4): understand the concept of [service]](/img/14/8de92a89d9c4b6476ac37408bc7788.png)
ROS2 series of knowledge (4): understand the concept of [service]
随机推荐
链式编程、包、访问权限
Soft Exam Senior System Architect Series: Basic Knowledge of System Development
机器学习初学者可以学哪些实战项目?
WebApi 打个Attribute 统一处理异常
修改Postman安装路径
初出茅庐的小李第112篇博客项目笔记之机智云智能浇花器实战(1)-基础Demo实现
pdb药物综合数据库
更换树莓派内核
OSF一分钟了解敏捷开发模式
OSD读取SAP CRM One Order应用日志的优化方式
opencv 缩小放大用哪种插值更好??
MYSQL master-slave replication
Raspberry pie arm version of GCC installed configuration and environment variables
WebApi hits an Attribute to handle exceptions uniformly
sqlserver cannot connect remotely
Chinese version of Pylint inspection rules
[cellular automata] based on matlab interface aggregation cellular automata simulation [including Matlab source code 2004]
手写二叉查找树及测试
July Bootcamp (Day 31) - Status Compression
开源项目站点必备&交流区功能