Ben Schreiber
Ben Schreiber

Reputation: 159

Typescript Decorator on method; get method in decorator

I am trying to make a decorator that can:

  1. Take a parameter
  2. Store the method it is above as a callable function
  3. Map the callable function with the parameter the decorator takes.

Here is what I tried:

class Foo {

    static cachedMethods: Map<string, (arg: string) => void> = new Map();

    static decorator = (decoratorArg: string) => (
        target: Object, 
        propertyKey: string,
        descriptor: TypedPropertyDescriptor<any>
        ): any => Foo.cachedMethods.set(decoratorArg, target as (arg: string) => void);

}

class Bar {
   @Foo.decorator("some data")
   method1(arg: string) {
      console.log(arg);
   }

   @Foo.decorator("some other data")
   method2(arg: string) {
       console.log(arg);
   }
}

let func: Function = Foo.cachedMethods.get("some data")!;
func("hello world");

However, it says that func is not a function. It is storing it as the Bar class. How can I store the method as a function?

Upvotes: 1

Views: 1466

Answers (1)

ghybs
ghybs

Reputation: 53185

The target 1st argument that is received by the decorator function is actually the class prototype. So in your case it will be Bar prototype.

https://www.typescriptlang.org/docs/handbook/decorators.html#method-decorators

The expression for the method decorator will be called as a function at runtime, with the following three arguments:

  1. Either the constructor function of the class for a static member, or the prototype of the class for an instance member.
  2. The name of the member.
  3. The Property Descriptor for the member.

Since you want to store a reference to the method, you can use target[propertyKey] or descriptor.value

Playground Link

Upvotes: 1

Related Questions