dq-charlie dq-charlie - 2 years ago 115
TypeScript Question

TypeScript: Decorators for Function Expressions

I am trying to add a function decorator to a function expression.
The decorator works for function declarations but not for function expressions.


function track(val: string) {

return function(_target: any, _key: string, descriptor: any) {

const originalMethod = descriptor.value;

descriptor.value = function(...args: any[]) {
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:

const handleClick = (e) => { console.log(e) };

I have experimentalDecorators flag on and targets ES5.

Answer Source

You can not decorate a function, you can ONLY decorate:

  • Class constructors
  • Class methods
  • Class method parameters
  • Class getters/setters
  • Class properties
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download