Level 19
Design Patterns
Classic design patterns — builder, factory, observer, singleton — take on new strength in TypeScript, where generics and unions let the compiler enforce the pattern's rules instead of relying on discipline.
30 min read + quiz
Patterns in a Structurally-Typed World
Design patterns were catalogued for class-heavy languages like Java and C++. TypeScript can express them the classic way, but its structural typing, first-class functions, and unions often allow lighter implementations: a 'strategy' is usually just a function type, and an 'adapter' is often a mapped object.
The valuable shift is using the type system to enforce the pattern's invariants. In Java, a builder that forgets a required field fails at runtime; in TypeScript, you can make the incomplete build a compile error. The pattern stops being convention and becomes contract.
Apply patterns to problems, not to code that lacks problems. The sections below pair each pattern with the specific pain it removes — if you do not have that pain, the simple function or object literal you already wrote is the better design.
// Strategy pattern, TypeScript-style: no interfaces, no classes.
type PricingStrategy = (base: number) => number;
const strategies: Record<string, PricingStrategy> = {
standard: (base) => base,
holiday: (base) => base * 0.8,
clearance: (base) => base * 0.5,
};
function price(base: number, strategy: PricingStrategy): number {
return strategy(base);
}
console.log(price(100, strategies.holiday)); // 80In TypeScript, many patterns collapse into function types.
Builder: Fluent Construction with Compile-Time State
The builder pattern constructs complex objects step by step with a fluent API. It shines when an object has many optional parts or when construction order matters — think query builders or HTTP request builders.
TypeScript's twist: each method can return a different generic instantiation of the builder, encoding what has been provided so far in the type. Calling build() before required steps then fails to compile. This 'type-state' technique moves an entire class of runtime errors into the editor.
Keep type-state builders for genuinely multi-step, order-sensitive construction. For a bag of options with defaults, a plain options object with Partial and a merge is simpler and just as safe.
class QueryBuilder<HasTable extends boolean = false> {
private table = "";
private conditions: string[] = [];
from(table: string): QueryBuilder<true> {
const next = new QueryBuilder<true>();
next.table = table;
next.conditions = [...this.conditions];
return next;
}
where(cond: string): QueryBuilder<HasTable> {
this.conditions.push(cond);
return this;
}
// build only exists once a table has been chosen:
build(this: QueryBuilder<true>): string {
const whereClause =
this.conditions.length > 0 ? " WHERE " + this.conditions.join(" AND ") : "";
return "SELECT * FROM " + this.table + whereClause;
}
}
const sql = new QueryBuilder().from("users").where("age > 18").build();
// new QueryBuilder().where("x").build(); // Error: 'this' is not QueryBuilder<true>The this-parameter trick makes premature build() a compile error.
Factory: Centralized, Type-Safe Creation
A factory centralizes object creation so callers depend on an interface rather than concrete classes. Use one when creation involves choices (which variant? which configuration?) that you do not want scattered across the codebase.
The TypeScript upgrade is connecting the factory's input to its output type. With a registry typed as a mapped object and a generic key parameter, createShape('circle') returns Circle — not a vague Shape — with zero casts at the call site.
Factories also pair naturally with discriminated unions: the factory takes the union's discriminant and returns the matching variant. When a new variant is added, the compiler flags the factory's non-exhaustive switch, so creation logic can never silently lag behind the type.
interface Circle {
kind: "circle";
radius: number;
}
interface Square {
kind: "square";
size: number;
}
type ShapeMap = {
circle: Circle;
square: Square;
};
const creators: { [K in keyof ShapeMap]: () => ShapeMap[K] } = {
circle: () => ({ kind: "circle", radius: 1 }),
square: () => ({ kind: "square", size: 1 }),
};
function createShape<K extends keyof ShapeMap>(kind: K): ShapeMap[K] {
return creators[kind]();
}
const c = createShape("circle"); // c: Circle — precise, no cast
console.log(c.kind, c.radius);A mapped registry links each key to its exact product type.
Observer: Typed Events
The observer pattern lets subscribers react to events without the publisher knowing who they are. It decouples modules — the shopping cart emits 'item-added' without importing the analytics, badge, and persistence code that listens.
The TypeScript essential is an event map: an interface from event name to payload type. Generic on and emit methods keyed by that map give every subscriber a correctly-typed payload and reject typo'd event names at compile time — the difference between EventEmitter misery and pleasant, discoverable APIs.
Two production concerns: always return an unsubscribe function (or accept an AbortSignal) so components can clean up and avoid leaks, and decide deliberately how listener exceptions are handled — one throwing listener should not silently stop the others.
type CartEvents = {
"item-added": { sku: string; qty: number };
"cart-cleared": undefined;
};
class Emitter<Events extends Record<string, unknown>> {
private listeners: { [K in keyof Events]?: Array<(p: Events[K]) => void> } = {};
on<K extends keyof Events>(event: K, fn: (p: Events[K]) => void): () => void {
const list = this.listeners[event] ?? [];
list.push(fn);
this.listeners[event] = list;
return () => {
this.listeners[event] = list.filter((l) => l !== fn);
};
}
emit<K extends keyof Events>(event: K, payload: Events[K]): void {
for (const fn of this.listeners[event] ?? []) {
fn(payload);
}
}
}
const cart = new Emitter<CartEvents>();
const off = cart.on("item-added", (p) => console.log("added", p.sku, "x" + p.qty));
cart.emit("item-added", { sku: "KB-01", qty: 2 });
off(); // clean upThe event map makes both names and payloads compile-checked.
Singleton: One Instance, Honestly Assessed
A singleton guarantees a single instance with global access — appropriate for genuinely unique resources like a configuration snapshot, a connection pool, or a logger. The classic TypeScript form uses a private constructor and a static getInstance, but a module-level constant is usually simpler: ES modules are evaluated once, so export const logger = new Logger() is already a singleton.
Singletons carry real costs, which is why they are the most criticized classic pattern. Hidden global state makes tests order-dependent, hides dependencies (nothing in a function's signature reveals it uses the singleton), and complicates parallel test runs. Every singleton is a little bit of spooky action at a distance.
The pragmatic middle ground is dependency injection with a default: functions accept the dependency as a parameter defaulting to the shared instance. Production code stays convenient, and tests pass a fake without monkey-patching modules.
class Logger {
private static instance: Logger | undefined;
private constructor(private prefix: string) {}
static getInstance(): Logger {
if (Logger.instance === undefined) {
Logger.instance = new Logger("[app]");
}
return Logger.instance;
}
log(msg: string): void {
console.log(this.prefix + " " + msg);
}
}
// Testable variant: inject with a default.
function processOrder(id: string, logger: Logger = Logger.getInstance()): void {
logger.log("processing " + id);
}
processOrder("ord_42"); // uses the shared instance
// In tests: processOrder("ord_42", fakeLogger);Default-parameter injection keeps singletons convenient and testable.
Try it yourself
This lesson's example is preloaded in the playground — break it, fix it, extend it.
Open in playgroundCheck your understanding
Question 1 · Multiple choice
What advantage does TypeScript add to the classic builder pattern?
Question 2 · Predict the output
What does this typed factory program print?
type Products = {
coffee: { kind: "coffee"; caffeine: number };
tea: { kind: "tea"; caffeine: number };
};
const make: { [K in keyof Products]: () => Products[K] } = {
coffee: () => ({ kind: "coffee", caffeine: 95 }),
tea: () => ({ kind: "tea", caffeine: 26 }),
};
function create<K extends keyof Products>(kind: K): Products[K] {
return make[kind]();
}
const drink = create("tea");
console.log(drink.kind, drink.caffeine);Question 3 · Find the error
This observer implementation compiles but has a real-world bug. What is it?
class Emitter {
private listeners: Array<(data: string) => void> = [];
on(fn: (data: string) => void): void {
this.listeners.push(fn);
}
emit(data: string): void {
for (const fn of this.listeners) {
fn(data);
}
}
}Question 4 · True or false
In an ES module environment, export const db = new Database() already behaves as a singleton, because modules are evaluated once and cached.
Question 5 · Multiple choice