当前位置:网站首页>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 也不迟 ~~~
边栏推荐
- 修改Postman安装路径
- OSD读取SAP CRM One Order应用日志的优化方式
- Guys, MySQL cdc source recycles replication slave and r in incremental process
- MYSQL-Batch insert data
- 机器学习应该如何入门?
- Soft Exam Senior System Architect Series: Basic Knowledge of Information Systems
- 785. 快速排序
- MYSQL two-phase commit
- 如何下载Keil包
- Lua introductory case of actual combat 1234 custom function and the standard library function
猜你喜欢
随机推荐
sqlserver无法远程连接
Nmap 操作手册 - 完整版
RTL8762DK RTC (5)
RTL8762DK Lighting/LED (3)
Chinese version of Pylint inspection rules
The fledgling Xiao Li's 114th blog project notes: Wisdom cloud intelligent flower watering device combat (3) - basic Demo implementation
Solve the problem that when IDEA creates a new file by default, right-click, new, there is no XML file
【消息通知】用公众号模板消息怎么样?
IDEA调试
IDEA 找不到或无法加载主类 或 Module “*“ must not contain source root “*“ The root already belongs to module “*“
leetcode: 1562. Find latest grouping of size M [simulation + endpoint record + range merge]
MYSQL-Batch insert data
OSD read SAP CRM One Order application log way of optimization
OSD读取SAP CRM One Order应用日志的优化方式
【入门教程】Rollup模块打包器整合
Fat interface in JQESAP system
how to edit the table of contents of an epub ebook
July Bootcamp (Day 31) - Status Compression
WebApi hits an Attribute to handle exceptions uniformly
初出茅庐的小李第114篇博客项目笔记之机智云智能浇花器实战(3)-基础Demo实现









