Ask Your Question
2

How can one define a TypeScript function for the purpose of decoration?

asked 2022-03-27 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-02-17 04:00:00 +0000

plato gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-03-27 11:00:00 +0000

Seen: 14 times

Last updated: Feb 17 '23