Reputation: 159
I am trying to make a decorator that can:
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
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:
- Either the constructor function of the class for a static member, or the prototype of the class for an instance member.
- The name of the member.
- The Property Descriptor for the member.
Since you want to store a reference to the method, you can use target[propertyKey]
or descriptor.value
Upvotes: 1