Advanced · 8 of 12 · 18 min read
Decorators
Two incompatible decorator systems, what each one receives, and why the version in most tutorials needs a compiler flag the standard one does not.
- Decorators
A decorator is a function that runs when a class is defined and gets to observe or replace what it decorates. TypeScript has shipped two different versions of them, and the first thing to establish in any conversation about decorators is which one is in play.
The two systems
| Legacy | Standard | |
|---|---|---|
| Enabled by | experimentalDecorators: true |
nothing — on by default in TS 5.0+ |
| Based on | an abandoned proposal draft | the TC39 proposal at stage 3 |
| Signature | (target, key, descriptor) |
(value, context) |
| Parameter decorators | yes | not yet |
| Metadata | via reflect-metadata and emitDecoratorMetadata |
context.metadata |
| Order of evaluation | bottom-up application | bottom-up application |
| Used by | Angular, NestJS, TypeORM, older MobX | new code, and gradually the frameworks |
| Will become JavaScript | no | yes |
Both can decorate a class, a method, an accessor and a field. Only the legacy system can decorate a parameter, which is precisely what constructor-based dependency injection relies on — and why Angular and NestJS have not moved.
Standard decorators
function logged<This, Args extends unknown[], Return>(
target: (this: This, ...args: Args) => Return,
context: ClassMethodDecoratorContext<This>,
) {
const name = String(context.name);
return function (this: This, ...args: Args): Return {
console.log(`calling ${name}`);
const result = target.call(this, ...args);
console.log(`${name} returned`, result);
return result;
};
}
class Calculator {
@logged
add(a: number, b: number) { return a + b; }
}
new Calculator().add(2, 3);
// calling add
// add returned 5
The shape is always the same: receive the thing, return a replacement or undefined. The second
argument carries the interesting information.
function inspect(target: unknown, context: DecoratorContext) {
console.log(context.kind); // "class" | "method" | "field" | "getter" | "setter" | "accessor"
console.log(context.name); // the member's name
console.log(context.addInitializer); // run code when the instance is constructed
return undefined;
}
class Example {
@inspect method() {}
}
console.log(new Example());
context.kind is what makes one decorator usable in several positions, and addInitializer is how
a method decorator does per-instance work — binding this, registering a listener, recording the
member in a registry.
function bound<This, Args extends unknown[], Return>(
target: (this: This, ...args: Args) => Return,
context: ClassMethodDecoratorContext<This>,
) {
context.addInitializer(function (this: This) {
const self = this as Record<string, unknown>;
self[String(context.name)] = target.bind(this);
});
}
class Counter {
#count = 0;
@bound
increment() { return ++this.#count; }
}
const counter = new Counter();
const detached = counter.increment; // no longer loses `this`
console.log(detached(), detached()); // 1 2
That is the entire content of the old @autobind, and it is the clearest example of what
decorators are for: a cross-cutting concern that would otherwise be repeated in every constructor.
Legacy decorators
Still worth being able to read, because most of the decorated code in the world is this:
// Requires "experimentalDecorators": true
function logged(
target: object,
key: string,
descriptor: PropertyDescriptor,
): PropertyDescriptor {
const original = descriptor.value as (...args: unknown[]) => unknown;
descriptor.value = function (...args: unknown[]) {
console.log(`calling ${key}`);
return original.apply(this, args);
};
return descriptor;
}
declare const d: typeof logged;
console.log(typeof d);
Three arguments: the prototype (or the constructor, for a static member), the member name, and the property descriptor. You mutate or return the descriptor. A class decorator instead receives the constructor and may return a replacement:
// Legacy class decorator.
function sealed<T extends { new (...args: never[]): object }>(constructor: T) {
Object.seal(constructor);
Object.seal(constructor.prototype);
return constructor;
}
declare const s: typeof sealed;
console.log(typeof s);
The source material for this track uses the legacy form throughout — and its tsconfig.json does
not set experimentalDecorators, so those examples would not compile as written. That is worth
knowing as a practical matter: a decorator example that errors with “Decorators are not valid here”
is almost always a flag mismatch rather than a syntax mistake.
Decorator factories
A decorator that takes arguments is a function returning a decorator:
function logged(prefix: string) {
return function <This, Args extends unknown[], Return>(
target: (this: This, ...args: Args) => Return,
context: ClassMethodDecoratorContext<This>,
) {
return function (this: This, ...args: Args): Return {
console.log(prefix, String(context.name));
return target.call(this, ...args);
};
};
}
class Service {
@logged("[api]")
fetch() { return "data"; }
}
new Service().fetch(); // [api] fetch
Every @Component({...}) and @Column({ type: "text" }) you have seen is this: the outer call
captures the configuration, the inner function is the decorator. The parentheses are the giveaway
— @logged applies a decorator, @logged("x") calls a factory that returns one.
Order
function first(label: string) {
console.log("evaluated", label);
return function (target: unknown, context: DecoratorContext) {
console.log("applied", label);
return undefined;
};
}
class Example {
@first("outer")
@first("inner")
method() {}
}
// evaluated outer
// evaluated inner
// applied inner
// applied outer
console.log(new Example());
Factories are evaluated top to bottom, decorators are applied bottom to top. The inner one
wraps first, so the outer one sees the already-wrapped method — the same composition order as
outer(inner(method)). When two decorators on one member interact, this is the detail that decides
the outcome.
Metadata and dependency injection
// Standard decorators: metadata is on the context.
function entity(name: string) {
return function (target: unknown, context: ClassDecoratorContext) {
context.metadata.table = name;
};
}
@entity("users")
class User {}
// console.log(User[Symbol.metadata]?.table); // "users"
console.log(typeof User);
The legacy equivalent needs reflect-metadata plus emitDecoratorMetadata, which makes the
compiler emit the types of parameters as runtime metadata. That is the mechanism behind
constructor injection: the framework reads the parameter types at runtime and resolves each one
from a container. It is the one place TypeScript types genuinely survive compilation — and they
survive because a compiler flag deliberately writes them out, not because the type system runs.
What they are good for, and what they are not
Decorators are at their best for a concern that is orthogonal to the code it decorates and repeated across many members: logging, timing, caching, validation, registration, access control.
They are a poor choice when the behaviour is part of what the method means, because they move it out of sight. Two practical warnings:
- A decorator that wraps a method makes the call stack and the step debugger less direct. Keep the wrapper thin.
- Decorator metadata is global mutable state in disguise. A registry populated by decorators at import time makes module load order significant, which is a hard class of bug to track down.
A higher-order function is often the simpler answer, and reads the same at the call site:
function withLogging<Args extends unknown[], Return>(
label: string,
fn: (...args: Args) => Return,
) {
return (...args: Args): Return => {
console.log(label);
return fn(...args);
};
}
const add = withLogging("add", (a: number, b: number) => a + b);
console.log(add(2, 3)); // add / 5
No flag, no compiler feature, no metadata, and it works on plain functions too. Reach for the decorator when the framework expects one or when the target really is a class member.
Common mistakes
Mixing the two systems
Mistake. Writing a (value, context) decorator in a project with
experimentalDecorators: true.
Why it fails. The compiler calls it with the legacy three arguments, so context is a string
and the decorator fails at class-definition time.
What to do instead. Check the tsconfig first. One project, one system; frameworks on legacy
decorators keep the flag until they migrate.
Forgetting to return the replacement
Mistake. A method decorator that builds a wrapper and never returns it.
Why it fails. Returning undefined means “keep the original”, so the decorator silently does
nothing.
What to do instead. Return the wrapper — and for per-instance work, use addInitializer
rather than returning anything.
Relying on decorator order by accident
Mistake. Two decorators on one method where one caches and the other validates. Why it fails. Application is bottom-up, so the lower decorator wraps first; swapping the two lines changes whether invalid input is cached. What to do instead. Write the order down where it matters, and avoid stacking decorators whose effects interact.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
What is a class decorator, at its simplest?
Decorators need a compiler flag, and the study file that teaches them does not set it.
A file using @Logger fails to compile with "Decorators are not valid here". What is missing?
@Logger
class Service {
fetch() { return "data"; }
}What does a decorator *factory* let you do?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.