TypeScript theorytheory 0/50 · 0%
Foundations · hard

43. Decorators (experimental & stage-3)

Annotating classes and members with reusable metadata/behaviour.

Decorators are functions applied to classes, methods, or properties with an `@` prefix, letting you wrap or annotate behaviour declaratively. TypeScript has long supported an experimental decorator proposal, and modern TypeScript also supports the newer, standardized (stage-3 / ES) decorators.

ts
function logCall(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const original = descriptor.value;
  descriptor.value = function (...args: any[]) {
    console.log(`Calling ${propertyKey} with`, args);
    return original.apply(this, args);
  };
  return descriptor;
}

class Vault {
  @logCall
  withdraw(amount: number) {
    return amount;
  }
}

Decorators are widely used by frameworks (Angular, NestJS, TypeORM) for dependency injection and metadata (`@Injectable()`, `@Column()`). They require enabling `experimentalDecorators` for the legacy proposal, or targeting a recent `target`/`tsconfig` setup for the newer standardized syntax; the two are not fully interchangeable.

Check your understanding

  1. 1. What is a decorator syntactically?

  2. 2. What compiler option enables the legacy experimental decorator proposal?

  3. 3. Which kinds of frameworks commonly rely heavily on decorators?