Home > database >  TypeScript Arrow functions and Decorators
TypeScript Arrow functions and Decorators

Time:12-15

I'm trying to workout whether its possible to decorate an arrow function in TypeScript like this example:

function decorateThisFunction() {        
    return (target: any, propertyKey: any, descriptor?: any) => {        
        console.log("This is my decorator do bar!");
    }
}

@decorateThisFunction
export const foo = (): void => {
    console.log("My Arrow Function");
};

If this isn't possible is there any alternative approaches people recommend?

CodePudding user response:

Quote from the official docs:

A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter.

So if you need a decorator you have to attach it to a class:

function decorateThisFunction(target: any, propertyKey: any, descriptor?: any): void {
    const originalMethod = descriptor.value;
    descriptor.value = function (...args: any[]) {
        console.log("This is my decorator do bar!");
        originalMethod(...args);
    }
}

class SomeClass {
    @decorateThisFunction
    static foo(): void {
        console.log("My Arrow Function");
    }
}

SomeClass.foo();

TypeScript playground

Without using a class you could simply use higher order functions:

function decorateThisFunction(func: (...args: any[]) => any) {
    return function(...args: any[]) {
        console.log("This is my decorator do bar!");
        func(...args);
    }
}

export const foo = decorateThisFunction((): void => {
    console.log("My Arrow Function");
});

foo();

TypeScript playground

  • Related