TypeScript-类装饰器

类装饰器

  • 类装饰器在类声明之前绑定(紧靠着类声明)
  • 类装饰器可以用来监视,修改或替换类的定义
  • 在执行类装饰器函数的时候, 会把绑定的类作为其唯一的参数传递给装饰器
function test(target: any) {
    console.log(target);
    target.prototype.personName = 'BNTang';
    target.prototype.say = (): void => {
        console.log(`my name is ${target.prototype.personName}`);
    }
}

@test
class Person {

}

interface Person {
    say(): void;
}

let p = new Person();
p.say();

image-20211205220618115

  • 如果类装饰器返回一个新的类,它会将新的类来替换原有类的定义
function test<T extends { new(...args: any[]): {} }>(target: T) {
    return class extends target {
        name: string = 'BNTang';
        age: number = 18;
    }
}

@test
class Person {

}

let p = new Person();
console.log(p);

image-20211205221201403

posted @ 2021-12-05 22:13  BNTang  阅读(98)  评论(0编辑  收藏  举报