Bogdan Surai
Bogdan Surai

Reputation: 1275

Decorators for functions

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.

Upvotes: 3

Views: 139

Answers (2)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249506

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(); 

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074138

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.

Upvotes: 3

Related Questions