Search code examples
typescriptsuperclasstypescript-decorator

Typescript superclass identifying from a decorator


I have an abstract class like the following

export abstract class Foo {
  public f1() {
  }
}

and two more classes extending the base

export class Boo extends Foo {
}

export class Moo extends Foo {
}

Now I have a custom decorator like the following

export function Bla() {
  return (target: any, key: string, descriptor: PropertyDescriptor) => {
  }
}

so my initial class is the following (with the decorator)

export abstract class Foo {
 @Bla
 public f1() {
 }
}

is there a way in the decorator to distinguish which call sourced from each superclass?

so far what I have tried are checking prototypes / constructors of target but I do not seem to find a way to access / understand from which class it was sourced. Is there a way to figure it out or I am doing something really wrong?

Thank you.


Solution

  • The trick to it is tapping into the method call itself and inspecting the class instance:

    function Bla(target: any, propKey: string | symbol | d: PropertyDescriptor) {
      let originalMethod = target[propKey];
    
      // return new property descriptor for the method, replacing the original one
      return {
        value: function () {
          let instance = this; // will be the instance ref because of 'function' literal
          let classReference = instance.constructor; // <-- this is what we need
    
          if (classReference === Boo) {
            // called from Boo class
          }
    
          // call original method
          return originalMethod.apply(this, arguments);
        }
      }
    }