Patterns & principles · 5 of 10 · 15 min read
The Strategy pattern
Interchangeable algorithms with a contract the compiler enforces — a Record over a literal union that makes a missing strategy a build error rather than an undefined.
- Design patterns
Strategy means several interchangeable ways of doing one job, chosen when the program runs. In JavaScript it is a lookup object of functions. TypeScript adds the part that was missing: a contract, and a guarantee that the lookup is complete.
The switch it replaces
type Method = "card" | "paypal" | "transfer";
function fee(method: Method, amount: number): number {
switch (method) {
case "card": return amount * 0.029 + 0.3;
case "paypal": return amount * 0.034 + 0.35;
case "transfer": return 0.25;
}
}
console.log(fee("card", 100).toFixed(2)); // 3.20
This is already better than the JavaScript version, because the union makes the switch provably
exhaustive — add "crypto" to Method and the function stops compiling for want of a return.
What it does not fix is that every new method edits this function, and that the fee logic lives
nowhere a test can reach it individually.
The typed lookup
type Method = "card" | "paypal" | "transfer";
interface FeeStrategy {
readonly label: string;
calculate(amount: number): number;
}
const strategies: Record<Method, FeeStrategy> = {
card: { label: "Card", calculate: (amount) => amount * 0.029 + 0.3 },
paypal: { label: "PayPal", calculate: (amount) => amount * 0.034 + 0.35 },
transfer: { label: "Transfer", calculate: () => 0.25 },
};
function fee(method: Method, amount: number): number {
return strategies[method].calculate(amount);
}
console.log(fee("paypal", 100).toFixed(2), strategies.card.label);
Three things the type system is now doing that it could not in JavaScript:
- The contract is named.
FeeStrategysays what a strategy must provide, so a new one is checked when it is written rather than when it is called. - The lookup is total.
Record<Method, FeeStrategy>requires every key. Add"crypto"toMethodand the object literal is an error until it is handled. - The index is safe.
strategies[method]needs no fallback and noundefinedcheck, becausemethodcan only be a key that exists.
That last point is the one that disappears the moment the key comes from outside the program.
When the key is untrusted
type Method = "card" | "paypal" | "transfer";
declare const strategies: Record<Method, { calculate(amount: number): number }>;
function isMethod(value: string): value is Method {
return value in strategies;
}
function fee(method: string, amount: number): number {
if (!isMethod(method)) throw new Error(`unknown payment method: ${method}`);
return strategies[method].calculate(amount);
}
console.log(typeof fee);
A type predicate over the lookup’s own keys, rather than a hand-written list that can fall behind.
This is the boundary: inside it the key is a Method and indexing is total; outside it, a string.
Interface or function type
Both are the pattern, and the choice is about how much a strategy carries:
| Strategy as | Spelling | Use when |
|---|---|---|
| A function type | type Fee = (amount: number) => number |
one behaviour, no state |
| An interface with one method | interface Fee { calculate(a: number): number } |
you also need a label, an id, metadata |
| An interface with several | validate, format, parse |
the strategies really do several related things |
| A class implementing it | class CardFee implements Fee |
each strategy has construction-time options |
// The lightest version, when a strategy is only behaviour:
type Comparator<T> = (a: T, b: T) => number;
const comparators = {
byName: (a: { name: string }, b: { name: string }) => a.name.localeCompare(b.name),
byAge: (a: { age: number }, b: { age: number }) => a.age - b.age,
} satisfies Record<string, Comparator<never>>;
const people = [{ name: "Beto", age: 25 }, { name: "Ana", age: 30 }];
console.log([...people].sort(comparators.byName).map((p) => p.name));
satisfies is the right operator here and : is not: it checks each entry against the contract
while keeping the exact key names, so comparators.byName stays usable and a typo in a key is
still an error.
Strategies with construction options
When a strategy needs configuration, a class or a factory is the natural form — and implements
makes the contract explicit:
interface Shipping {
readonly label: string;
cost(weightKg: number): number;
}
class FlatRate implements Shipping {
readonly label = "Flat rate";
constructor(private readonly rate: number) {}
cost() { return this.rate; }
}
class PerKilo implements Shipping {
readonly label = "Per kilo";
constructor(private readonly perKg: number, private readonly minimum = 0) {}
cost(weightKg: number) { return Math.max(this.perKg * weightKg, this.minimum); }
}
const options: Shipping[] = [new FlatRate(5), new PerKilo(1.2, 3)];
console.log(options.map((option) => `${option.label}: ${option.cost(10)}`));
The same with closures instead of classes, which is often lighter and types identically:
interface Shipping { readonly label: string; cost(weightKg: number): number }
const flatRate = (rate: number): Shipping => ({
label: "Flat rate",
cost: () => rate,
});
const perKilo = (perKg: number, minimum = 0): Shipping => ({
label: "Per kilo",
cost: (weightKg) => Math.max(perKg * weightKg, minimum),
});
console.log(perKilo(1.2, 3).cost(10));
implements versus returning the interface type: both are checked, and the closure version needs
no this. Prefer it unless you want inheritance between strategies.
Making the strategy decide its own arguments
The problem the JavaScript version cannot solve: strategies that need different inputs. A discriminated union of inputs plus a mapped lookup types each one correctly:
type Payment =
| { method: "card"; number: string; cvc: string }
| { method: "paypal"; email: string }
| { method: "transfer"; iban: string };
type Handlers = {
[M in Payment["method"]]: (payment: Extract<Payment, { method: M }>) => string;
};
const handlers: Handlers = {
card: (payment) => `card ending ${payment.number.slice(-4)}`,
paypal: (payment) => `paypal ${payment.email}`,
transfer: (payment) => `transfer ${payment.iban}`,
};
function describe<P extends Payment>(payment: P): string {
return (handlers[payment.method] as (value: P) => string)(payment);
}
console.log(describe({ method: "paypal", email: "a@b.c" }));
Each handler receives exactly its own variant — payment.email is available in the paypal
handler and nowhere else. That is Strategy and discriminated unions doing one job together, and it
is the shape behind every typed reducer, router and message dispatcher.
Open/Closed, concretely
type Method = "card" | "paypal" | "transfer" | "crypto"; // 1. add the case
interface FeeStrategy { calculate(amount: number): number }
const strategies: Record<Method, FeeStrategy> = {
card: { calculate: (amount) => amount * 0.029 },
paypal: { calculate: (amount) => amount * 0.034 },
transfer: { calculate: () => 0.25 },
crypto: { calculate: (amount) => amount * 0.01 }, // 2. add the strategy
};
// 3. nothing else changes, and step 2 was not optional
console.log(strategies.crypto.calculate(100));
In JavaScript, forgetting step 2 produces undefined is not a function at runtime, in production,
for the one customer who chose the new method. Here it is a red squiggle. That difference is the
reason to reach for the typed form of the pattern.
Common mistakes
Record<string, Strategy> instead of the union
Mistake. Typing the lookup with string keys because it is easier.
Why it fails. Totality is gone, indexing yields a value that may not exist, and nothing
connects the lookup to the set of cases. It is the JavaScript version with extra syntax.
What to do instead. A literal union as the key type, and a predicate at the boundary where
untrusted keys arrive.
Annotating with : where satisfies was wanted
Mistake. const strategies: Record<string, Comparator> = { byName, byAge }.
Why it fails. The annotation widens the keys, so strategies.byName is no longer known to
exist and a typo in a key name is accepted.
What to do instead. satisfies, which checks the entries and keeps the literal keys.
A strategy interface that grows a method for one implementation
Mistake. Adding requiresRedirect() to FeeStrategy because PayPal needs it.
Why it fails. Every other strategy now implements a method that means nothing to it — the
Interface Segregation failure, caught here by the compiler demanding the member everywhere.
What to do instead. A separate optional capability interface, or a discriminated union of
strategy shapes when they genuinely differ.
Check yourself
One question from the bank on what you just read. Answering here does not affect your quiz history.
What does TypeScript add to the Strategy pattern that JavaScript cannot express?
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.