1. // 类的装饰器
    2. // 装饰器本身是一个函数
    3. // 类装饰器接受的参数是构造函数
    4. // 装饰器通过 @ 符号来使用
    5. function testDecorator(flag: boolean) {
    6. if (flag) {
    7. return function(constructor: any) {
    8. constructor.prototype.getName = () => {
    9. console.log('dell');
    10. };
    11. };
    12. } else {
    13. return function(constructor: any) {};
    14. }
    15. }
    16. @testDecorator(true)
    17. class Test {}
    18. const test = new Test();
    19. (test as any).getName();
    1. function testDecorator() {
    2. return function<T extends new (...args: any[]) => any>(constructor: T) {
    3. return class extends constructor {
    4. name = 'lee';
    5. getName() {
    6. return this.name;
    7. }
    8. };
    9. };
    10. }
    11. const Test = testDecorator()(
    12. class {
    13. name: string;
    14. constructor(name: string) {
    15. this.name = name;
    16. }
    17. }
    18. );
    19. const test = new Test('dell');
    20. console.log(test.getName());