I am trying to add a function decorator to a function expression. The decorator works for function declarations but not for function expressions.
Decorator:
function track(val: string) {
return function(_target: any, _key: string, descriptor: any) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
Logger.log(val);
originalMethod.apply(this, args);
};
return descriptor;
};
Function expression which I'm trying to annotate: It will not work if I try to decorate like this:
const handleClick = @track('trackMe') (e) => { console.log(e) };
or this:
@trackMetric('sdf')
const handleClick = (e) => { console.log(e) };
I have experimentalDecorators flag on and targets ES5.
In TypeScript, you can create decorators using the special syntax @expression , where expression is a function that will be called automatically during runtime with details about the target of the decorator. The target of a decorator depends on where you add them.
A Decorator is a special kind of declaration that can be applied to classes, methods, accessor, property, or parameter.
Decorators provide a way to annotate or modify a class or class member in TypeScript. However, Decorators are still an experimental feature of the language. To learn more about Decorators in TypeScript, visit the Decorators proposal page.
It's possible to use as many decorators on the same piece of code as you desire, and they'll be applied in the order that you declare them. This defines a class and applies three decorators — two to the class itself, and one to a property of the class: @log could log all access to the class.
You can not decorate a function, you can ONLY decorate:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With