All academies
Roadmap/Advanced

Level 14

Decorators

Modern (TC39 stage 3, TypeScript 5+) decorators let you wrap and annotate classes and their members declaratively, replacing boilerplate like logging, memoization, and registration with reusable annotations.

25 min read + quiz

What Decorators Are (and Which Version You're Using)

A decorator is a function applied to a class or class member with @name syntax. It receives the thing being decorated plus a context object, and can replace or augment it. Conceptually, @logged class Foo is sugar for Foo = logged(Foo, context) — a transformation applied at class-definition time.

There are two incompatible decorator systems in the wild. The legacy 'experimental' decorators (enabled by experimentalDecorators in tsconfig) power older Angular and NestJS code. TypeScript 5 implements the TC39 standard decorators, which need no flag and have a different, better-designed API built around a context object. This lesson covers the modern standard.

The context object is what makes modern decorators pleasant: it tells you the member's kind ('class', 'method', 'getter', 'field', 'accessor'), its name, whether it is static or private, and gives you addInitializer for running setup code per instance. Always check context.kind if a decorator could be misapplied.

type ClassMethodContext = ClassMethodDecoratorContext;

function readonlyName(
  target: object,
  context: ClassDecoratorContext
): void {
  // A class decorator can observe or replace the class.
  console.log("Decorating class: " + String(context.name));
}

@readonlyName
class Report {
  title = "Q3";
}

A decorator runs once, when the class definition is evaluated.

Method Decorators: Wrapping Behavior

The most common decorator pattern is wrapping a method: the decorator receives the original function and returns a replacement that adds behavior before and after calling it. Logging, timing, retry logic, and permission checks all follow this exact shape.

Inside the replacement, this must be forwarded correctly. Use a regular function (not an arrow function) for the replacement so it picks up the caller's this, and invoke the original with original.call(this, ...args). Getting this wrong is the number-one decorator bug.

Because decorators are just higher-order functions, you can unit test them without any class at all: call the decorator with a fake method and context, then call the returned function. Design them as pure wrappers and they stay easy to reason about.

function logged<This, Args extends unknown[], Return>(
  original: (this: This, ...args: Args) => Return,
  context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>
) {
  const name = String(context.name);
  return function (this: This, ...args: Args): Return {
    console.log("Calling " + name);
    const result = original.call(this, ...args);
    console.log("Finished " + name);
    return result;
  };
}

class Calculator {
  @logged
  add(a: number, b: number): number {
    return a + b;
  }
}

The replacement function wraps the original, preserving this and types.

Decorator Factories: Configurable Decorators

A bare decorator takes no arguments of its own. When you write @retry(3), retry is not a decorator — it is a decorator factory: a function that returns a decorator. The extra layer lets callers configure behavior per use site.

The evaluation order trips people up: factory calls run top-to-bottom (their arguments are evaluated in source order), but the resulting decorators are applied bottom-up, innermost first. @a @b method means a(b(method)) — b wraps the method, then a wraps that.

Factories are where decorators earn their keep in real codebases: @throttle(200), @cache({ ttl: 60 }), @requiresRole('admin'). Each call site reads as a declarative statement of policy, and the implementation lives in exactly one place.

function retry(attempts: number) {
  return function <This, Args extends unknown[], Return>(
    original: (this: This, ...args: Args) => Return,
    _context: ClassMethodDecoratorContext
  ) {
    return function (this: This, ...args: Args): Return {
      let lastError: unknown;
      for (let i = 0; i < attempts; i++) {
        try {
          return original.call(this, ...args);
        } catch (err) {
          lastError = err;
        }
      }
      throw lastError;
    };
  };
}

class Fetcher {
  @retry(3)
  load(): string {
    if (Math.random() < 0.5) throw new Error("flaky");
    return "data";
  }
}

retry(3) returns the actual decorator — a factory in action.

Field and Accessor Decorators

Field decorators work differently from method decorators: the field does not exist yet when the decorator runs, so instead of receiving a value, the decorator may return an initializer transformer — a function that receives the initial value per instance and returns the (possibly modified) value to actually store.

The accessor keyword, introduced alongside standard decorators, turns a field into a getter/setter pair backed by private storage. Accessor decorators receive that get/set pair and can replace either, enabling reactive-style interception the way legacy property decorators never cleanly could.

Use addInitializer on the context when you need per-instance setup, such as auto-binding a method to its instance so it can be passed as a callback. This replaces the constructor boilerplate of this.onClick = this.onClick.bind(this).

function uppercase<This>(
  _target: undefined,
  _context: ClassFieldDecoratorContext<This, string>
) {
  return function (this: This, initial: string): string {
    return initial.toUpperCase();
  };
}

class Badge {
  @uppercase
  label = "beta";
}

const badge = new Badge();
console.log(badge.label); // "BETA"

A field decorator transforms the initial value of every instance.

When (Not) to Use Decorators

Decorators excel at cross-cutting concerns — behavior that applies uniformly across many methods or classes: logging, metrics, caching, validation, dependency registration. If you are copy-pasting the same wrapper logic into many methods, a decorator centralizes it.

They are a poor fit for core business logic. Hiding essential behavior behind an annotation makes control flow invisible at the call site; a reader of processPayment should not have to know that @audited @transactional silently changes what the method does on failure. Keep decorators for infrastructure, not domain rules.

Also remember that decorators cannot change a member's TypeScript type as seen by callers. A decorator that makes a method return a Promise where it did not before will compile but lie to every caller. If the wrapper changes the signature, use an explicit higher-order function instead so types stay honest.

// Good: infrastructure concern, signature unchanged.
// @cached(60)
// getExchangeRates(): Rates { ... }

// Bad idea: decorator secretly changes behavior a caller must know about.
// @swallowsErrors
// chargeCard(amount: number): Receipt { ... }

// If the signature must change, prefer an explicit wrapper:
function withTiming<Args extends unknown[], R>(
  fn: (...args: Args) => R
): (...args: Args) => { result: R; ms: number } {
  return (...args) => {
    const start = Date.now();
    const result = fn(...args);
    return { result, ms: Date.now() - start };
  };
}

Signature-changing wrappers should be explicit functions, not decorators.

Try it yourself

This lesson's example is preloaded in the playground — break it, fix it, extend it.

Open in playground

Check your understanding

Question 1 · Multiple choice

What is the key difference between TypeScript 5 standard decorators and legacy experimental decorators?

Question 2 · Predict the output

Two method decorators are stacked. In what order do the log lines appear when greet() is called?

function tag(label: string) {
  return function <This, Args extends unknown[], R>(
    original: (this: This, ...args: Args) => R,
    _ctx: ClassMethodDecoratorContext
  ) {
    return function (this: This, ...args: Args): R {
      console.log(label);
      return original.call(this, ...args);
    };
  };
}

class T {
  @tag("outer")
  @tag("inner")
  greet(): void {
    console.log("body");
  }
}
new T().greet();

Question 3 · Find the error

This logging decorator has a bug that breaks methods using this. What is it?

function logged<This, Args extends unknown[], R>(
  original: (this: This, ...args: Args) => R,
  _ctx: ClassMethodDecoratorContext
) {
  return (...args: Args): R => {
    console.log("calling");
    return original.call(undefined as This, ...args);
  };
}

Question 4 · True or false

A method decorator can change the method's signature — for example, making it return a Promise — and callers will see the new type.

Question 5 · Multiple choice

In @retry(3), what exactly is retry?