Decorators for functions

Viewed 71

As I see, decorators usually can be used with classes and methods inside classes. Is there a way to use decorators with regular functions like in code below:

@myDecorator()
function someFunction() {
  // do something
}

someFunction(); // running the function with the decorator.
2 Answers

Not with the current proposal. Decorating stand-alone functions, object initializers and their contents, or other things may well be follow-on proposals, but the current proposal only allows decorating classes and their contents.

Decorators are not supported on functions as per the current proposal

You can acrive a similar result using a simple function call:

function myDecorator<Args extends any[], R>(fn: (...a: Args)=> R): (...a:Args) =>R {
    return function (...a: Args) {
        console.log("Calling");
        return fn(...a);
    } 
}
const someFunction = myDecorator(function () {
    console.log("Call");
});

someFunction(); 
Related