Patterns & principles · 8 of 10 · 16 min read
The Decorator pattern
Wrapping an object to add behaviour without changing it — and why this has almost nothing to do with TypeScript's @decorator syntax.
- Design patterns
The Decorator pattern wraps an object in another object with the same interface, adding
behaviour on the way through. TypeScript’s @decorator syntax is a language feature that
modifies a class member at definition time. They share a name and very little else.
The difference, stated
| The pattern | The @ syntax |
|
|---|---|---|
| What it wraps | an object instance | a class, method, field or accessor |
| When | at runtime, per instance | once, when the class is defined |
| Needs a language feature | no | yes |
| Composes by | nesting objects | stacking annotations |
| Granularity | the whole interface | one member |
| Can be chosen per instance | yes | no — fixed for the class |
| Typical use | caching, retry, logging around a client | framework metadata, binding, validation |
That “per instance” row is the practical reason to prefer the pattern: two instances of the same class can have different decorations, which an annotation cannot express.
The pattern
interface DataSource {
read(key: string): Promise<string | null>;
}
class HttpDataSource implements DataSource {
async read(key: string) {
console.log("fetching", key);
return `value for ${key}`;
}
}
class CachingDataSource implements DataSource {
#cache = new Map<string, string | null>();
constructor(private readonly inner: DataSource) {}
async read(key: string) {
if (this.#cache.has(key)) return this.#cache.get(key) ?? null;
const value = await this.inner.read(key);
this.#cache.set(key, value);
return value;
}
}
class LoggingDataSource implements DataSource {
constructor(private readonly inner: DataSource) {}
async read(key: string) {
const started = Date.now();
const value = await this.inner.read(key);
console.log(`read ${key} in ${Date.now() - started}ms`);
return value;
}
}
const source: DataSource = new LoggingDataSource(new CachingDataSource(new HttpDataSource()));
await source.read("a"); // fetching a, then the log line
await source.read("a"); // only the log line — the cache answered
console.log(typeof source.read);
Three classes, one interface, and the decorations compose in whatever order the caller nests them.
implements DataSource on each wrapper is what makes it safe: a wrapper that forgets a method, or
changes a signature, fails to compile — and DataSource is the only type any consumer sees.
Order is a decision with consequences. Logging(Caching(Http)) logs every call including cache
hits; Caching(Logging(Http)) logs only the calls that reach the network. Both are reasonable and
they answer different questions.
Composing with functions
For a single-method interface, a function is lighter and types the same:
type Reader = (key: string) => Promise<string | null>;
const http: Reader = async (key) => `value for ${key}`;
const withCache = (inner: Reader): Reader => {
const cache = new Map<string, string | null>();
return async (key) => {
if (!cache.has(key)) cache.set(key, await inner(key));
return cache.get(key) ?? null;
};
};
const withRetry = (inner: Reader, attempts = 3): Reader => async (key) => {
for (let attempt = 1; attempt <= attempts; attempt++) {
try {
return await inner(key);
} catch (error) {
if (attempt === attempts) throw error;
}
}
return null;
};
const read = withCache(withRetry(http));
console.log(await read("a"));
Same pattern, no classes. The type Reader is the interface, and each decorator is a function from
Reader to Reader — which is also why they compose without any further machinery.
Decorating a whole interface generically
When the interface has many methods and the decoration is uniform, writing a wrapper per method
gets tedious. A Proxy with a mapped type keeps it typed:
interface Api {
getUser(id: string): Promise<{ id: string }>;
listUsers(): Promise<readonly { id: string }[]>;
}
function withLogging<T extends object>(target: T, label: string): T {
return new Proxy(target, {
get(object, property, receiver) {
const value = Reflect.get(object, property, receiver);
if (typeof value !== "function") return value;
return (...args: unknown[]) => {
console.log(label, String(property), args);
return value.apply(object, args);
};
},
});
}
declare const api: Api;
const logged = withLogging(api, "[api]");
console.log(typeof logged.getUser); // still typed as Api
Proxy<T> returns T, so the decoration is invisible to the type system — which is both the
convenience and the warning. Nothing checks that the proxy preserves the contract, so a bug in the
handler is a runtime bug. Use it for genuinely uniform cross-cutting work; write explicit wrappers
when the behaviour differs per method.
Mixins: the class-level version
A mixin adds members to a class rather than wrapping an instance, and it is the answer to “I want
several independent capabilities and I only have one extends”:
type Constructor<T = object> = new (...args: any[]) => T;
function Timestamped<TBase extends Constructor>(Base: TBase) {
return class extends Base {
createdAt = new Date();
age() { return Date.now() - this.createdAt.getTime(); }
};
}
function Serialisable<TBase extends Constructor>(Base: TBase) {
return class extends Base {
toJSON() { return { ...this }; }
};
}
class Entity {
constructor(public id: string) {}
}
class Document extends Serialisable(Timestamped(Entity)) {}
const doc = new Document("d1");
console.log(doc.id, doc.age() >= 0, doc.toJSON());
A mixin is a function from a constructor to a class, and the composition is nested calls — exactly
the shape of the decorator functions above. What it gives over extends is that the capabilities
are independent and reusable: Timestamped works on any class, and nothing has to be arranged
into a single hierarchy.
The costs are real and worth naming: the resulting class name is anonymous in stack traces, the
any[] in Constructor is required by the compiler and loses constructor-argument checking, and a
deep stack of mixins produces a type that editors render unhelpfully. Two or three is comfortable;
six is not.
The declaration-merging variant, for when you want the type without the inheritance chain:
class Widget {
render() { return "widget"; }
}
interface Widget extends Disposable {} // declared here, implemented below
interface Disposable { dispose(): void }
Object.assign(Widget.prototype, {
dispose() { console.log("disposed"); },
});
new Widget().dispose();
The interface merges into the class’s type, and Object.assign supplies the implementation. It is
compact, and nothing connects the two halves except your diligence — the same caveat as every
declaration.
Choosing
- One behaviour, one method → a function from
ReadertoReader. - One behaviour, several methods, differing per method → a wrapper class with
implements. - Uniform behaviour over a large interface → a
Proxy, accepting that it is unchecked. - Capabilities on a class, not an instance → mixins.
- Framework metadata, binding, registration → the
@syntax, because the framework asks for it.
Common mistakes
Confusing the two
Mistake. Answering “the Decorator pattern” with an explanation of @Component.
Why it fails. They are different ideas: one wraps objects at runtime and needs no language
support, the other modifies class members at definition time.
What to do instead. Name both, say which one the question is about, and give the wrapper
example — it is the pattern.
A wrapper that does not implement the interface
Mistake. A caching class with just the methods it wanted to intercept.
Why it fails. It is not substitutable: anything using another method of the interface breaks,
and without implements nothing says so until a call site fails.
What to do instead. implements the full interface and forward what you do not change. If
there are many methods, that tedium is the signal to use a Proxy.
Mixins as the primary structure
Mistake. Six mixins composed into every model class.
Why it fails. The type becomes unreadable, the construction order matters in ways nothing
documents, and super calls through the chain are hard to follow.
What to do instead. Two or three focused mixins, and plain composition — a field holding a
collaborator — for the rest.
Check yourself
2 questions from the bank on what you just read. Answering here does not affect your quiz history.
The Decorator *pattern* and TypeScript’s @decorator — the same thing?
What does the mixin pattern give you in TypeScript that extends cannot?
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.