DEV Community

Jeferson Eiji
Jeferson Eiji

Posted on • Originally published at dev.to

Understanding Decorators in TypeScript: A Clear and Practical Guide

What Are Decorators in TypeScript?

Decorators are a special kind of declaration in TypeScript that can be attached to classes, methods, accessors, properties, or parameters. They allow you to add annotations or meta-programming syntax for class declarations and members.

Think of decorators as functions that wrap or modify pieces of your code.

How Decorators Work

  • A decorator is a function applied to the thing it decorates (class, method, property, etc).
  • Decorators receive information about the decorated element, such as the target, key, and descriptor.
  • You can use them to alter behavior, add metadata, or even replace functionality.

Note: Decorators are an experimental feature and require "experimentalDecorators": true in tsconfig.json.

Types of Decorators

  • Class Decorators
  • Property Decorators
  • Method Decorators
  • Parameter Decorators

Example: Class and Method Decorators

// A simple class decorator
function Logger(constructor: Function) {
  console.log(`New instance created: ${constructor.name}`);
}

@Logger
class ExampleClass {
  sayHello() {
    console.log('Hello!');
  }
}
Enter fullscreen mode Exit fullscreen mode

What happens: When an instance of ExampleClass is created, the Logger function logs the class name.

Method Decorator Example:

function LogMethod(target: Object, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;
  descriptor.value = function (...args: any[]) {
    console.log(`Called ${propertyKey} with`, args);
    return originalMethod.apply(this, args);
  };
}

class Calculator {
  @LogMethod
  add(a: number, b: number) {
    return a + b;
  }
}
// When you call new Calculator().add(1,2), it logs: "Called add with [1,2]"
Enter fullscreen mode Exit fullscreen mode

Summary

  • Decorators are a powerful way to modify or annotate code in TypeScript.
  • They help with logging, validation, dependency injection, and more.
  • Always enable experimentalDecorators in your configuration file to use them.

Top comments (0)