Decorators

Advanced · 12 min

TypeScript 5's standard decorators, the (value, context) signature, field and accessor decorators, and how legacy experimentalDecorators differs.

Before thisClasses and access modifiersFunction type expressions and call signaturesWhy generics, and generic functions

Cloudaffle · 12 min

Decorators

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CloudaffleReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A decorator is a function applied to a class or class member with `@` syntax when the class is defined; it can observe the member, replace it, or register code to run later.
  • TypeScript 5.0 implements the TC39 standard decorators, which receive two arguments: the decorated value and a `context` object describing it.
  • `context.kind` says what was decorated (`class`, `method`, `getter`, `setter`, `field` or `accessor`), and `context.name`, `context.static` and `context.private` describe it further.
  • A method decorator can return a replacement function, a field decorator can return a function that transforms the initial value, and an `accessor` decorator can return new `get` and `set` behaviour.
  • `context.addInitializer` registers a callback that runs for each instance during construction (or once, for static members and classes), which is how a `@bound` decorator can bind methods.
  • Standard decorators can't decorate constructor or method parameters; parameter decorators exist only in the legacy system.
  • The legacy system, enabled with `experimentalDecorators`, uses a different `(target, propertyKey, descriptor)` signature, and `emitDecoratorMetadata` adds runtime type information; NestJS projects still use it, and older framework code was written against it.

The problem: the same wrapper on every method

Say you want to log every call to a handful of methods. You could edit each method to print on entry and exit, but that’s the same five lines copied everywhere, and it buries the method’s real work. What you want is to write the wrapper once and attach it by name. That’s a decorator: a function the class definition calls on a member, which can hand back a replacement.

A first decorator

Since TypeScript 5.0, decorators follow the TC39 standard proposal. A decorator receives two things: the value being decorated, and a context object describing it.

function logged<This, Args extends unknown[], Return>(
  target: (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(`-> ${name}(${args.join(", ")})`);
    const result = target.call(this, ...args);
    console.log(`<- ${name}`);
    return result;
  };
}

class Cart {
  items: string[] = [];

  @logged
  add(item: string) {
    this.items.push(item);
    return this.items.length;
  }
}

new Cart().add("apple");
// -> add(apple)
// <- add

logged runs once, when Cart is defined. It returns a new function, and that function replaces add on the class. It’s a closure over target, so it can still call the original. The generics are there so the replacement keeps add’s exact parameter and return types; a decorator typed with any everywhere would compile too, but it would hide mistakes.

Think of it as a mail room stamping parcels as they arrive. The stamp is applied once, at the door. Whatever was stamped goes on to its destination with the stamp attached.

The context object

The second argument is what makes standard decorators practical. context.kind tells you what was decorated: "class", "method", "getter", "setter", "field" or "accessor". context.name is the member’s name, and context.static and context.private say whether it’s static or a #private member. TypeScript gives each kind its own context type, such as ClassMethodDecoratorContext or ClassFieldDecoratorContext, so a decorator can only be applied where its signature fits.

The context also has addInitializer, for work that needs an instance. A decorator runs before any instance exists, so it can’t bind a method to this. An initializer can, because it runs during construction:

function bound<This extends object>(
  _target: (this: This, ...args: any[]) => any,
  context: ClassMethodDecoratorContext<This>,
) {
  const name = context.name as keyof This;
  context.addInitializer(function () {
    const method = this[name] as (...args: unknown[]) => unknown;
    this[name] = method.bind(this) as This[keyof This];
  });
}

class Counter {
  count = 0;

  @bound
  increment() {
    this.count++;
  }
}

const c = new Counter();
const inc = c.increment;
inc(); // works: `this` is still c

That fixes the lost-this problem from typing this and callbacks for any method you mark.

Fields, accessors, and factories

Each kind of member has its own return rule. A method decorator returns a replacement method. A field decorator returns a function that receives the initial value and returns a new one, so it can transform the starting value but not later writes. To intercept every read and write, declare the field with the accessor keyword. That gives it a hidden storage slot with a getter and setter, and an accessor decorator can wrap them:

function clamp(min: number, max: number) {
  return function <This>(
    target: ClassAccessorDecoratorTarget<This, number>,
    context: ClassAccessorDecoratorContext<This, number>,
  ): ClassAccessorDecoratorResult<This, number> {
    return {
      set(value) {
        target.set.call(this, Math.min(max, Math.max(min, value)));
      },
    };
  };
}

class Speaker {
  @clamp(0, 10)
  accessor volume = 5;
}

const sp = new Speaker();
sp.volume = 42;
sp.volume; // 10

clamp(0, 10) is a decorator factory: a function that takes settings and returns the decorator. The @ expression is evaluated first, then its result is applied.

What standard decorators can’t do

There are no parameter decorators:

declare function Inject(token: string): (...args: any[]) => void;

class Mailer {
  constructor(@Inject("SMTP_URL") url: string) {} // Error: Decorators are not valid here.
}

That one omission is why the older system is still around.

Legacy decorators: experimentalDecorators

TypeScript shipped decorators years before the standard settled, behind the experimentalDecorators flag. Those legacy decorators have a different signature: a member decorator gets the class prototype, the member’s name, and its property descriptor, and edits the descriptor. They also allow parameter decorators. Pair them with emitDecoratorMetadata, and the compiler records each constructor’s parameter types at runtime under keys like design:paramtypes, readable through the reflect-metadata library.

function legacyLogged(
  target: object,
  propertyKey: string,
  descriptor: PropertyDescriptor,
) {
  const original = descriptor.value;
  descriptor.value = function (this: unknown, ...args: unknown[]) {
    console.log(`-> ${propertyKey}`);
    return original.apply(this, args);
  };
}

declare function Inject(token: string): ParameterDecorator;

class Mailer {
  constructor(@Inject("SMTP_URL") private url: string) {}

  @legacyLogged
  send(to: string) {
    return `${to} via ${this.url}`;
  }
}

That metadata is how NestJS’s dependency injection knows what to pass each constructor. Angular is its own case: its compiler reads @Component and friends at build time and compiles them away, so those decorators follow Angular’s rules rather than either TypeScript mode; the Angular roadmap covers what those decorators do. The two systems aren’t interchangeable. The flag switches the whole project, and a decorator written for one won’t work under the other. For new code outside those frameworks, use standard decorators.

About the video

Cloudaffle’s video is built around this lesson’s main contrast. It explains what decorators are, then compares the legacy decorators of TypeScript 4 with the standard decorators that arrived in TypeScript 5. It doesn’t cover decorator metadata, added in TypeScript 5.2. Watch it after the sections above. The Andrew Burgess video below is a closer look at the standard API’s context object and replacement model, and the Concise Developer course works through every decorator kind at length.

Check yourself

  1. 01Your tsconfig has no `experimentalDecorators` setting. Which decorator system does TypeScript 5 use, and what arguments does a method decorator receive?

    The standard (TC39) decorators. A method decorator receives the original method and a `ClassMethodDecoratorContext` object with `kind: "method"`, the method's `name`, flags such as `static` and `private`, and `addInitializer`.

  2. 02A method decorator returns a new function. What happens to the original method?

    The returned function replaces it on the class. The original is only reachable if the replacement keeps a reference to it, which is why a logging decorator closes over `target` and calls `target.call(this, ...args)` inside the wrapper.

  3. 03Why does a `@bound` decorator use `context.addInitializer` instead of binding the method directly in the decorator body?

    The decorator runs once, when the class is defined, before any instance exists, so there is no `this` to bind to. An initializer runs for each new instance during construction, where `this` is that instance, so it can assign a bound copy of the method onto it.

  4. 04What is the `accessor` keyword for, and why do accessor decorators need it?

    `accessor volume = 5` declares a field backed by an automatically generated private storage slot with a getter and setter. A decorator on it receives that `get` and `set` pair and can return wrapped versions, which lets it intercept every read and write of the field. A plain field decorator can only transform the initial value.

  5. 05You copy `constructor(@Inject("SMTP_URL") url: string)` from a NestJS project into a project using standard decorators. What happens, and why?

    It fails with "Decorators are not valid here." The standard proposal has no parameter decorators; they only exist under `experimentalDecorators`. NestJS also depends on `emitDecoratorMetadata` to read constructor parameter types, so such code needs the legacy settings.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark