当前位置:网站首页>带你体验一次类型编程实践
带你体验一次类型编程实践
2022-08-01 02:31:00 【小鑫同学】
写作背景:
在看 uniapp 的教程时看到大量的 API 还是使用的 callback 的方式来接收 API 的执行结果,大量的 API 嵌套使用又会造成回调地狱的现象出现,在 API Promise 化 这一篇中提到了有部分API是已经做了 Promise 化,我这边用 cli 命令初始化的 vite+ts 的项目发现没办法使用对应的 Promise 化 API,所以还是通过一个工具类来实现一下,顺便试着再写一写 TypeScript 类型编程代码。
工具类编写准备:
下面这块代码我相信你有过类似想法的 jym 应该在网上看到过,通过定义这样一个高阶函数来将uniapp api 进行包装,并在执行这个高阶函数返回的函数时使用 Promise 来接管 api 成功失败所对应的回调函数。
export const promisify = (api) => {
return (options, ...params) => {
return new Promise((resolve, reject) => {
api(Object.assign({}, options, {
success: resolve,
fail: reject
}), ...params);
});
}
}
注:高阶函数说的简单点就是传入一个函数并返回一个函数,切记返回的是函数还没有执行,遇到了多少写防抖节流的小伙伴是忘了执行还各个群里问 why 的~
发挥TypeScript类型的强大之处:
Typescript内置类型工具:
Parameters :提取函数类型的参数所组成的类型列表; NonNullable :提取传入类型除 null、undefined 以外的类型;
类型编程分析:
promisify 函数的输入类型约束:输入的内容均是uniapp api(函数),所以使用泛型来约束输入的类型;
const promisify = <P extends (...args: any) => any>(api: P) => {}
promisify 返回的函数的输入类型约束:这个输入类型实际是 uniapp api 执行的的形参类型,所以需要使用内置的类型工具(1)来提取,我们只提取类型列表的第一项即可,有实际需要可以再扩展:
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 对象的类型约束:这里只能通过泛型约束成功状态的类型,成功状态的类型实际上是 uniapp api 选项中 success 属性(回调函数)返回的类型。我们需要先提取到 success 属性,然后再次使用内置类型工具(1)来提取回调函数的返回类型。
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
*/
/**
* 提取传入函数的第一个形参参数的类型
*/
type ParameterFirst<T extends (...args: any) => any> = Parameters<T>[0];
/**
* 提取传入函数的第一个形参参数中key为success的参数的类型;
* 因success类型为函数类型,所以再次提取success函数的第一个形参参数的类型
*/
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 来编写项目,就要尽可能的发挥出 TypeScript 作用,在万般无奈的时候再用 any 也不迟 ~~~
边栏推荐
- Rasa 3.x Study Series - Rasa - Issues 4918 Study Notes
- How to get started with YOLO?How to implement your own training set?
- ECCV2022 Workshop | Multi-Object Tracking and Segmentation in Complex Environments
- Four ways the Metaverse is changing the way humans work
- The device node structure is converted into a platform_device structure
- date command
- MYSQL Keyword Explain Analysis
- Game Security 03: A Simple Explanation of Buffer Overflow Attacks
- HCIP(15)
- leetcode: 1562. Find latest grouping of size M [simulation + endpoint record + range merge]
猜你喜欢

Key Points Estimation and Point Instance

普通用户无法访问hgfs目录

初出茅庐的小李第112篇博客项目笔记之机智云智能浇花器实战(1)-基础Demo实现

数据中台建设(七):数据资产管理

Raspberry pie arm version of GCC installed configuration and environment variables

Flink 部署和提交job

MYSQL master-slave replication

Summary of MVCC

如何下载Keil包
![ROS2 series of knowledge (4): understand the concept of [service]](/img/14/8de92a89d9c4b6476ac37408bc7788.png)
ROS2 series of knowledge (4): understand the concept of [service]
随机推荐
Device tree - conversion from dtb format to struct device node structure
MYSQL query interception optimization analysis
Rasa 3.x Study Series - Rasa - Issues 4898 Study Notes
OSD read SAP CRM One Order application log way of optimization
如何下载Keil包
SC7A20 (Silan Micro-Accelerometer) Example
链式编程、包、访问权限
WebApi 打个Attribute 统一处理异常
Chinese version of Pylint inspection rules
纽约大学等 | TM-Vec:用于快速同源检测和比对的模版建模向量
How to get started with YOLO?How to implement your own training set?
RTL8762DK PWM(七)
Daily practice of LeetCode - Circular linked list question (interview four consecutive questions)
Blueprint: Yang Hui's Triangular Arrangement
Super like the keyboard made from zero, IT people love it
How is the tree structure of the device tree reflected?
RTL8762DK WDG(六)
High dimensional Gaussian distribution basics
OSF一分钟了解敏捷开发模式
Introduction to machine learning how to?