What It Is
The Strategy pattern makes an algorithm swappable: the surrounding code stays the same, and the interchangeable part — how to price, how to sort, how to compress — is plugged in as a value.
TypeScript can write a strategy two ways: as a class implementing an interface, or as a plain function type. This page uses the function type, because the strategy here is one calculation with no state of its own — type Pricing = (price: number) => number and an assignment are the whole mechanism.
Example: Swappable Pricing
Shop never changes; the pricing rule is a function value in a field. Regular price, Black Friday, member discount — three functions, one shop.
The strategy is a function value
Three checkouts of the same 50 give three totals — 50.00, 35.00 and 45.00 — and only the assigned function differs. This is also how sorting works: array.sort(compare) takes the comparison strategy.
Output: TypeScript file and captured output
// The strategy is a function type — any matching function fits.
type Pricing = (price: number) => number
const regular: Pricing = (price) => price
const blackFriday: Pricing = (price) => price * 0.7
const member: Pricing = (price) => price - 5
class Shop {
pricing: Pricing
constructor(pricing: Pricing) {
this.pricing = pricing
}
checkout(price: number): void {
console.log("total:", this.pricing(price).toFixed(2))
}
}
const shop = new Shop(regular)
shop.checkout(50)
shop.pricing = blackFriday
shop.checkout(50)
shop.pricing = member
shop.checkout(50)
When to Use It
Use it whenever an algorithm varies while its surroundings do not: pricing rules, retry policies, sorting orders, validation modes.
Skip it when there is one algorithm and no realistic second. Use the interface-and-class form instead of a function only when a strategy needs its own state or several methods.
Pros and Cons
Pros: behavior swaps at run time; each strategy is small and testable alone; as a function type it is nearly free — one type alias and an assignment.
Cons: the chosen strategy is invisible at the call site — debugging means finding what was assigned; too many micro-strategies fragment simple logic.