Skip to content
AgileLogics
4 min read

Design Patterns in TypeScript

Prerequisites: Classes with types, Generics

TypeScript's interfaces make classic design patterns easy to express with real compile-time guarantees. A common example, the Strategy pattern:

interface PaymentStrategy {
    pay(amount: number): void;
}

class CreditCardPayment implements PaymentStrategy {
    pay(amount: number) {
        console.log(`Paid $${amount} by credit card`);
    }
}

function checkout(strategy: PaymentStrategy, amount: number) {
    strategy.pay(amount);
}

checkout doesn't care which concrete payment method it receives — only that it satisfies PaymentStrategy — letting new payment methods be added without changing checkout at all.