当前位置:网站首页>Typescript decorator is basically used
Typescript decorator is basically used
2022-06-12 19:27:00 【Chasing the dream_ informal essay】
typescript Class decorator
1. Class decorator itself is a function
2. The decorator executes after the decorated class executes
3. The decorator of the class accepts that the first parameter is a constructor
4. Multiple decorators perform the sequence , Top to bottom or left to right , The decoration is executed from bottom to top or from right to left
tsconfig.json Inner opening decorator :
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
/*
Decorator implements analog interface request
*/
const RequestDecorotor = (url: string): MethodDecorator => {
return (...args:any[]) => {
const [, , descriptor] = args;
const methods = descriptor.value;
descriptor.value = () => {
new Promise((resolve) => {
setTimeout(() => {
resolve({ name: ' Lao Wang ', age: 28,url });
},200)
}).then(res => {
methods(res)
})
}
}
}
class MockRequest {
@RequestDecorotor('https://xxx.com')
public resultData(res:any={}) {
console.log(" Request the results ", res)
// { name: ' Lao Wang ', age: 28, url: 'https://xxx.com' }
}
}
new MockRequest().resultData();
/*
Decorator processing error
*/
const errDecorotor: MethodDecorator = (...args:any[]) => {
const [, , descriptor] = args;
const methods = descriptor.value;
descriptor.value = () => {
try {
methods();
} catch (error) {
// Custom styles and error handling
console.log(`%c${error}`, `color: red;cont-size:50px`);
}
}
}
class ErrorDeal {
@errDecorotor
public find() {
throw new Error(' The file you are looking for does not exist ')
}
@errDecorotor
public login() {
throw new Error(' Your login permission is insufficient ')
}
}
const err = new ErrorDeal();
err.find();
err.login();
/*
The decorator factory is in ts Use
You can pass parameters to the decorator , for example
*/
const tankDecorotor = (type:string):ClassDecorator => {
console.log(type)
if (type === 'Tank3') {
return (target: Function) => {
target.prototype.moveTank = () => {
console.log('moveTank')
}
}
}
//player3
return (target:Function) => {
target.prototype.playerSing = () => {
console.log('playerSing')
}
}
}
@tankDecorotor('Tank3')
class Tank3 {
}
@tankDecorotor('player3')
class Player3{
}
// call
const t3 = new Tank3();
(<any>t3).moveTank();
const player3 = new Player3();
(<any>player3).playerSing();
/*
Print
Tank3
player3
moveTank
playerSing
*/
边栏推荐
- review. JS ppt math formula cannot be displayed
- Hardware test - why not use grounding clip for ripple test
- ISCC2022
- synchronized下的 i+=2 和 i++ i++执行结果居然不一样
- Wincc7.5 SP1 method for adjusting picture size to display resolution
- Redis中的事务
- Shell programming regular expressions and metacharacters
- Rhca memoirs -- Introduction to cl280
- Module 8 operation
- [image denoising] image denoising based on anisotropic filtering with matlab code
猜你喜欢

Transactions in redis

【图像去噪】基于正则化实现图像去噪附matlab代码

What is data driven
![[matrix theory & graph theory] final exam review mind map](/img/7f/ea23970c613bbb366d9d840c6c175b.png)
[matrix theory & graph theory] final exam review mind map

RT thread simulator builds lvgl development and debugging environment

Attack and defense world (WEB) -- supersqli

The component style set by uniapp takes effect in H5 and app, but does not take effect in wechat applet. The problem is solved
![leetcode:6097. Match [set record + query one by one with the same length] after replacing characters](/img/03/d8286742bacf25b62c7dc3dcb0733e.png)
leetcode:6097. Match [set record + query one by one with the same length] after replacing characters

API call display, detailed API of Taobao, tmall and pinduoduo commodity pages, and return of APP side original data parameters

Wincc7.5 SP1 method for adjusting picture size to display resolution
随机推荐
合理地配置线程池
no available service ‘null‘ found, please make sure registry config correct
How does Eldon's ring of the law get lune quickly? Introduction to the fastest and safest method for obtaining lune
leetcode:5289. Distribute cookies fairly [see data range + DFS pruning]
CVPR 2022 oral Dalian Institute of technology proposed SCI: a fast and powerful low light image enhancement method
【刷题笔记】线段树
Analysis report on market demand and investment strategy of China's re guarantee industry 2022-2028
Implementation of VGA protocol based on FPGA
In 2021, the global fire pump drive power revenue is about $381million, and it is expected to reach $489.3 million in 2028
Dacom G150双模耳机,为爱发声,呵护孩子听力健康成长
review.js ppt数学公式无法显示
基于微信电子书阅读小程序毕业设计毕设作品(7)中期检查报告
【生成对抗网络学习 其三】BiGAN论文阅读笔记及其原理理解
Detailed explanation of yolox network structure
Leetcode 494. Objectives and
leetcode:6094. Company name [group enumeration + cannot repeat set intersection + product Cartesian product (repeat indicates length)]
Native servlet - upload & download of files
Meituan won the first place in fewclue in the small sample learning list! Prompt learning+ self training practice
API call display, detailed API of Taobao, tmall and pinduoduo commodity pages, and return of APP side original data parameters
从16页PPT里看懂Jack Dorsey的Web5