In TypeScript, a function can be decorated by using the '@' symbol and followed by the name of the decorator function. The decorator function can be defined as a regular function that takes in the target function as its argument and returns a new function that wraps the original function.
Here's an example of a decorator function that logs the name of the function being decorated:
function logFunction(targetFunc: Function) {
const originalFunc = targetFunc;
const funcName = originalFunc.name;
targetFunc = function(...args: any[]) {
console.log(`Function ${funcName} called with arguments ${args}`);
return originalFunc.apply(this, args);
}
return targetFunc;
}
To use the decorator, apply it to the function you want to decorate:
@logFunction
function myFunction(arg1, arg2) {
// function logic goes here
}
Now, every time myFunction
is called, it will also log its name and arguments to the console.
Asked: 2022-03-27 11:00:00 +0000
Seen: 14 times
Last updated: Feb 17 '23