How to properly wrap constructors with decorators in TypeScript

后端 未结 5 1987
猫巷女王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

    0 讨论(0)
  • 2020-12-28 08:57

    This code works for me:

    function logClass(target: any) {
      // save a reference to the original constructor
      var original = target;
    
      // the new constructor behaviour
      var f : any = function (...args) {
        console.log("New: " + original.name); 
        //return  original.apply(this, args);
        return new original(...args); // according the comments
      }
    
      // copy prototype so intanceof operator still works
      f.prototype = original.prototype;
    
      // return new constructor (will override original)
      return f;
    }
    
    @logClass
    class Base {
        prop: number = 5;
    }
    
    class Extended extends Base {
        constructor() {
            super()
        }
    }
    
    var b = new Base()
    console.log(b.prop)
    
    var a = new Extended()
    console.log(a.prop)
    
    0 讨论(0)
  • 2020-12-28 09:03

    This is the more modern approach using the latest TS (3.2.4). The below also uses the decorator factory pattern so you can pass in attributes:

    function DecoratorName(attr: any) {
      return function _DecoratorName<T extends {new(...args: any[]): {}}>(constr: T){
        return class extends constr {
          constructor(...args: any[]) {
            super(...args)
            console.log('Did something after the original constructor!')
            console.log('Here is my attribute!', attr.attrName)
          }
        }
      }
    }
    

    See here for more info: https://www.typescriptlang.org/docs/handbook/decorators.html#class-decorators

    0 讨论(0)
  • 2020-12-28 09:08

    If you like run code after and before constructor() with a decorator:

    function ClassWrapper() {
        return function(target: any) {
            // save a reference to the original constructor
            var original = target;
    
            // the new constructor behaviour
            var f: any = function (...args) {
                console.log('ClassWrapper: before class constructor', original.name);
                let instance = original.apply(this, args)
                console.log('ClassWrapper: after class constructor', original.name);
                return instance;
            }
    
            // copy prototype so intanceof operator still works
            f.prototype = original.prototype;
    
            // return new constructor (will override original)
            return f;
        };
    }
    @ClassWrapper()
    export class ClassExample {
        public constructor() {
            console.info('Running ClassExample constructor...');
        }
    }
    
    let example = new ClassExample();
    
    /*
    CONSOLE OUTPUT:
    ClassWrapper: before class constructor ClassExample
    Running ClassExample constructor...
    ClassWrapper: after class constructor ClassExample
    */
    
    0 讨论(0)
  • 2020-12-28 09:12

    The comments in the other answers complain that code doesn't work.
    Actually, it works, but not in jsFiddle...
    It is an issue with the code generation in jsFiddle (perhaps using an obsolete version of TypeScript).
    The code above works with TypeScript 2.7.2 (run with Node).

    So this is basically the code in pablorsk's answer (except there is no need to return the instance), I just added full types to please a stricter TSLint...

    function logClass<T extends { new(...args: any[]): {} }>(): any {
        type Ctor = new (...args: any[]) => T;
        return (target: T): Ctor => {
            // Save a reference to the original constructor
            const Original = target;
    
            // the new constructor behaviour
            let decoratedConstructor: any = function (...args: any[]): void {
                console.log("Before construction:", Original);
                Original.apply(this, args);
                console.log("After construction");
            };
    
            // Copy prototype so intanceof operator still works
            decoratedConstructor.prototype = Original.prototype;
            // Copy static members too
            Object.keys(Original).forEach((name: string) => { decoratedConstructor[name] = (<any>Original)[name]; });
    
            // Return new constructor (will override original)
            return decoratedConstructor;
        };
    }
    
    @logClass()
    class Base {
        prop = 5;
        constructor(value: number) {
            console.log("Base constructor", value);
            this.prop *= value;
        }
        foo() { console.log("Foo", this.prop); }
        static s() { console.log("Static s"); }
    }
    
    class Extended extends Base {
        constructor(init: number) {
            super(init);
            console.log("Extended constructor", init);
        }
        bar() { console.log("Bar", this.prop); }
    }
    
    const b = new Base(2);
    console.log("Base", b instanceof Base);
    b.foo();
    Base.s();
    
    const e = new Extended(5);
    console.log("Extended", e instanceof Base, e instanceof Extended);
    e.bar();
    

    [EDIT] Also added a line copying static members, otherwise decorated class throws an error when calling the static method.

    0 讨论(0)
提交回复
热议问题