从下往上执行,所以name的值会覆盖

    1. // 创建一个泛型:new (...args: any[]) => any 这是一个构造函数,返回 any 类型,接收任意的参数,每个参数的类型不做约束
    2. // 现在 constructor 的类型是一个泛型,这个泛型可以通过实例化创建出一个类,这个类应该包含一个构造函数
    3. function testDecorator<T extends new (...args: any[]) => any>(constructor: T) {
    4. // 对构造函数进行扩展
    5. return class extends constructor {
    6. name = "zbl";
    7. };
    8. }
    9. @testDecorator
    10. class Test {
    11. name: string;
    12. constructor(name: string) {
    13. this.name = name;
    14. getName() {
    15. return this.name;
    16. }
    17. }
    18. }
    19. let test = new Test("zws");
    20. console.log(test); // class_1 { name: 'zbl' }
    21. console.log((test as any).getName());

    因为 getName 是装饰器“偷偷”加进来的,所以现在我们调用实例上的方法会报错,通过类型断言的方式可以使其不报错,但这样显然是不对的:

    1. function testDecorator() {
    2. return function <T extends new (...args: any[]) => any>(constructor: T) {
    3. return class extends constructor {
    4. name = "zbl";
    5. getName() {
    6. return this.name;
    7. }
    8. };
    9. };
    10. }
    11. // 将装饰器以函数的方式执行,用装饰器去直接修饰 class,生成一个新的类,给到 Test
    12. const Test = testDecorator()(
    13. class {
    14. name: string;
    15. constructor(name: string) {
    16. this.name = name;
    17. }
    18. }
    19. );
    20. let test = new Test("zws");
    21. // 不报错,并且有提示
    22. console.log(test.getName());