dq-charlie
dq-charlie

Reputation: 247

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.

Upvotes: 9

Views: 7718

Answers (2)

Michelle Oliveira
Michelle Oliveira

Reputation: 109

You can write a method and decorate this method with your factory like this:

As such, the following steps are performed when evaluating multiple decorators on a single declaration in TypeScript:

The expressions for each decorator are evaluated top-to-bottom. The results are then called as functions from bottom-to-top. If we were to use decorator factories, we can observe this evaluation order with the following example:

function f() {
    console.log("f(): evaluated");
    return function (
            target,
            propertyKey: string,
            descriptor: PropertyDescriptor
        ) {
        console.log("f(): called");
    };
}

function g() {
    console.log("g(): evaluated");
    return function (
        target,
        propertyKey: string,
        descriptor: PropertyDescriptor
    ) {
        console.log("g(): called");
    };
}

class C {
    @f()
    @g()
    method() {}
}

Which would print this output to the console:


You should read this: Decorators in Typescript

Upvotes: 1

gilamran
gilamran

Reputation: 7294

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

  • Class constructors
  • Class methods
  • Class method parameters
  • Class getters/setters
  • Class properties

Upvotes: 18

Related Questions