TypeScript 装饰器介绍
TypeScript 的装饰器主要是用于记录某些类型元信息和业务逻辑,装饰器不一定要实现实现业务逻辑,因为它的最大作用还是语法糖,以便代码和库的使用者可以方便地重用某些逻辑。装饰器的执行顺序是自上而下
执行。接下来我们通过几个简单的例子看看 TypeScript 的装饰器是怎么使用的。
TypeScript 开启装饰器支持
TypeScript 的装饰器默认是关闭的,所以我们需要手动开启,具体代码如下:
"experimentalDecorators": true,
TypeScript 类装饰器
/**
* 类装饰器只需传入目标类作为参数即可,然后就可以在目标类的基础上进行相应的操作
*/
function Component(target: Function) {
target.prototype.id = 100;
}
@Component
export class TestClass {
static elementId: string;
id: number;
printId(prefix: string = ""): string {
return prefix + this.id;
}
}
console.log(new TestClass().id);
或者可以传入相应的参数进行操作,例如:
function Component(option: { id: string }) {
return (target: Function & typeof TestClass) => {
target.elementId = option.id;
};
}
@Component({ id: "200" })
export class TestClass {
static elementId: string;
id: number;
printId(prefix: string = ""): string {
return prefix + this.id;
}
}
console.log(TestClass.elementId);
TypeScript 方法装饰器
/**
* @param target 当前的原型对象
* @param propertyKey 方法接受参数的关键字
* @param propertyDesriptor 装饰器装饰的方法描述,
*/
function MethodTest(target: Object, propertyKey: string, propertyDesriptor: PropertyDescriptor) {
console.log(target)
console.log(propertyKey)
console.log(propertyDesriptor)
propertyDesriptor.value = function (...args: any[]) {
return `Hello ${args}`
}
}
@MethodTest
printId(prefix: string = ''): string {
return prefix + this.id
}
TypeScript 属性装饰器
function PropTest(target: Object, propertyName: string) {
let value: number;
const getter = () => {
console.log(`获取值${value}`);
return value;
};
const setter = (newVal: number) => {
console.log(`设置值${newVal}`);
value = newVal;
};
Object.defineProperty(target, propertyName, { get: getter, set: setter });
}
@PropTest
id: number
TypeScript 方法参数装饰器
function MethodPropTest(target: Object, propertyName: string, index: number) {
console.log('-------')
console.log(target)
console.log(propertyName)
console.log(index)
console.log('-------')
}
gateArea(width: number, @MethodPropTest height: number) {
return width * height
}