TypeScript ยท Chapter 40 of 44

TypeScript Decorators

Decorators are a special kind of declaration that can be attached to classes, methods, properties, or parameters to add extra behavior or metadata, using an `@expression` syntax.

Decorators are commonly used in frameworks like Angular and NestJS to add functionality such as dependency injection or routing information. They require enabling `experimentalDecorators` in tsconfig.json.

Syntax
function Logger(target: Function) {
  console.log(`Class created: ${target.name}`);
}

@Logger
class MyClass {}

Class decorators

A class decorator is a function that receives the class constructor and can observe, modify, or replace it, applied by writing `@decoratorName` right above the class declaration.

Method decorators

A method decorator can wrap or modify how a method behaves, such as logging every time it's called, by receiving the target, method name, and property descriptor.

Example 1 (typescript)
function Logger(target: Function) {
  console.log(`Class created: ${target.name}`);
}

@Logger
class Greeter {
  greet() {
    return "Hi!";
  }
}
Output
Class created: Greeter

The Logger decorator runs once when the Greeter class is defined, logging its name.

Example 2 (typescript)
function LogMethod(target: any, key: string, descriptor: PropertyDescriptor) {
  const original = descriptor.value;
  descriptor.value = function (...args: any[]) {
    console.log(`Calling ${key}`);
    return original.apply(this, args);
  };
}
class Calc {
  @LogMethod
  add(a: number, b: number) {
    return a + b;
  }
}
console.log(new Calc().add(2, 3));
Output
Calling add
5

The method decorator wraps add() to log a message every time it's called.

Key points

  • Decorators use `@expression` syntax above a declaration.
  • They can be applied to classes, methods, properties, and parameters.
  • Decorators require enabling experimentalDecorators in tsconfig.json.
  • Frameworks like Angular and NestJS rely heavily on decorators.
๐Ÿ’ก Note: Decorators are an advanced, evolving feature โ€” check your framework's documentation for the exact usage expected.

๐Ÿ“ Quick Quiz

1. What symbol starts a decorator?

2. What tsconfig option is required to use decorators?

3. Which frameworks commonly use decorators?