Reputation: 1609
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?
Upvotes: 1
Views: 2857
Reputation: 365
The answer to this question changed with TypeScript 5+ since TS switched to the syntax proposed for ECMAScript decorators.
The --emitDecoratorMetadata
flag is no longer required and the code to obtain the class name has changed. The easiest way to obtain it now appears to be to rely on the calling this
.
function logMethodExec<This, Args extends any[], Return>(target: (this: This, ...args: Args) => Return, context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>) {
const methodName = String(context.name);
return function(this: This, ...args: Args): Return {
console.log(`Going to execute ${(this as object).constructor.name}.${methodName}()`);
return target.apply(this, args);
};
}
Though, as mentioned before, this won't work if the code gets minified. If the above code is used in conjunction with a minifier, the class name will be minified. The method name on the other hand remains unaffected as it is provided by the context
.
Souce: Decorators - TypeScript 5
Upvotes: 0
Reputation: 2050
You should be careful in relying on that. Minifying bundlers tend to change object names, which could through off the logic. See this page for more info - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#telling_the_constructor_name_of_an_object
Upvotes: 1
Reputation: 4451
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);
};
};
};
Upvotes: 2