Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 465
Bogdan Surai Avatar asked Sep 18 '26 11:09

Bogdan Surai


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.

like image 108
T.J. Crowder Avatar answered Sep 20 '26 00:09

T.J. Crowder


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(); 
like image 39
Titian Cernicova-Dragomir Avatar answered Sep 20 '26 02:09

Titian Cernicova-Dragomir