Search code examples
typescriptannotations

How to get the class name from a typescript annotation


I am using typescript annotations at method level. I would like to be able to get the class or file name from the annotation.

const some = (arg: string) => {
  return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
    const originalMethod = descriptor.value;
    descriptor.value = function (...args: any[]) {
      // get class name here <------------------------
      const result = originalMethod.apply(this, args);
      return result;
    };
  };
};


class Foo(){

  @some("xyz")  
  bar(){
    // do something
  }
}

Any idea?


Solution

  • For an instance member, the decorator is called with the prototype of the class.

    function some(arg: string) {
      return (targetPrototype: any, propertyKey: string, descriptor: PropertyDescriptor) => {
        const originalMethod = descriptor.value;
        const className = targetPrototype.constructor.name;
        descriptor.value = function (...args: any[]) {
            console.log(className);
        };
      };
    };