How to properly wrap constructors with decorators in TypeScript

后端 未结 5 1998
猫巷女王i
猫巷女王i 2020-12-28 08:32

The process of wrapping a class with a decorator causes superclasses to be unable to access that classes\' properties. Why?

I have some code that:

  1. Crea
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-28 08:52

    A solution using ES2015 Proxy to override the constructor:

    function wrap(target: any) {
      return new Proxy(target, {
        construct(clz, args) {
          console.log(`Constructing ${target.name}`);
          return Reflect.construct(clz, args);
        }
      });
    }
    
    @wrap
    class Base {
      prop: number = 5;
    }
    
    class Extended extends Base {
      constructor() {
        super()
      }
    }
    
    var a = new Extended()
    console.log(new Extended().prop);
    

    You can also run this on StackBlitz

提交回复
热议问题