1、装饰器定义
装饰器是一种特殊的类型声明,它可以附加在类、方法、属性、参数上边
需开启tsconfig.json中 "experimentalDecorators":true
生成tsconfig.json文件
tsc -init
2、类装饰器
// 类装饰器 主要是通过@符号添加装饰器
// 装饰器会自动把class的构造函数传入到装饰器的第一个参数target
// 然后通过prototype可以自定义添加属性和方法function decotators (target:any) {target.prototype.name = 'test';
}@decotators
class Test {constructor () {}
}const test: any = new Test();console.log(test.name);
2、属性装饰器
// 属性装饰器
// 使用@符号给属性添加装饰器
// 它会返回两个参数 1、原型对象 2、属性的名称const currency: PropertyDecorator = (target: any, key: string | symbol) => {console.log(target, key);
}class Test {@currencypublic name: stringconstructor () {this.name = 'test';}getName () {return this.name;}
}const test = new Test();
3、参数装饰器
// 参数装饰器
// 使用@符号给属性添加装饰器
// 它会返回三个参数 1、原型对象 2、方法的名称 3、参数的位置从0开始const currency: ParameterDecorator = (target: any, key: string | symbol, index: number) => {console.log(target, key, index);
}class Test {public name: stringconstructor () {this.name = '';}getName (name: string, @currency age: number) {return this.name;}
}
4、方法装饰器
// 方法装饰器
// 它会返回两个参数 1、原型对象 2、方法的名称
// 属性描述符 可写:writable 可枚举:enumerable 可配置:configurableconst currency: MethodDecorator = (target: any, key: string | symbol, descriptor) => {console.log(target, key, descriptor);
}class Test {public name: stringconstructor() {this.name = ''}@currencygetName(name:string, age:number){return this.name;}
}
5、自定义装饰器
添加配置、安装依赖
npm init -y tsc -init npm install axios -S
import axios from "axios";// 定义装饰器
const Get = (url: string): MethodDecorator => {return (target, key, descriptor: PropertyDescriptor) => {const fnc = descriptor.value;axios.get(url).then(res => {fnc(res, { status: 200 })}).catch(e => {fnc (e, { status: 500 })})}
}// 定义控制器
class Controller {constructor(){}@Get('https://api.apiopen.top/api/getHaoKanVideo?page=0&size=10')getList (res: any, status: any){console.log(res.data.result.list, status);}
}