Language: EN

typescript-que-son-y-como-usar-decoradores

What are and how to use decorators in TypeScript

Decorators in TypeScript are a syntax for special functions that are applied to a class, method, property, or parameter to modify or add additional behaviors.

These functions are executed at compile time and can perform tasks such as modifying the functionality of a method, tracking calls to a method, validating input parameters (among many other things).

Creating a basic decorator

To create a decorator in TypeScript, we simply need to define a function with the name of the decorator and apply it to the class, method, property, or parameter we want to decorate. For example,

function logMethod(target: any, key: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;

  descriptor.value = function (...args: any[]) {
    console.log(`Method ${key} called with arguments ${args}`);
    return originalMethod.apply(this, args);
  };

  return descriptor;
}

In this example, we define a function called logMethod that takes three parameters:

  • target, which is the class to which the decorator is applied
  • key, which is the name of the decorated method
  • descriptor, which is an object that contains information about the decorated method

On the other hand, in the body of this function:

  • We keep a reference to the original method
  • We redefine the method to print a log message before calling the original method
  • Finally, we return the modified descriptor

Applying a decorator

Once we have created our decorator, we can apply it to the class, method, property, or parameter we want to decorate using the @ symbol followed by the name of the decorator.

Let’s see this by continuing the previous example, showing how to apply the logMethod decorator to a method of a class:

class MyClass {
  @logMethod
  myMethod(arg1: string, arg2: number) {
    console.log(`Method myMethod called with arguments ${arg1} and ${arg2}`);
  }
}

In this example,

  • We apply the logMethod decorator to the myMethod of the MyClass
  • When myMethod is called, the decorator will print a log message before executing the original method code.