Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 207
dq-charlie Avatar asked Aug 17 '17 07:08

dq-charlie


People also ask

How do I create a decorator for functions in TypeScript?

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.

What can decorators be applied to TypeScript?

A Decorator is a special kind of declaration that can be applied to classes, methods, accessor, property, or parameter.

Are decorators still experimental in TypeScript?

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.

How many decorators can be applied to a declaration?

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.


1 Answers

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

  • Class constructors
  • Class methods
  • Class method parameters
  • Class getters/setters
  • Class properties
like image 144
gilamran Avatar answered Sep 24 '22 19:09

gilamran