SOLID Principles in TypeScript
The five SOLID object-oriented design principles with concise TypeScript examples and links to Bridge and Dependency Inversion.
TL;DR
SOLID is five principles for keeping code easy to change: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. Together they push you toward small, focused interfaces where high-level logic does not break when low-level details change.
Why it exists
As a codebase grows, unrelated features tangle together: editing tax rules breaks PDF formatting, adding a payment provider requires modifying five switch statements, and unit tests need a real database just to test order validation. SOLID gives concrete rules to prevent that coupling.
Mental model
Each principle targets a specific axis of coupling:
| Letter | Principle | Core rule |
|---|---|---|
| S | Single Responsibility | One cohesive reason to change |
| O | Open/Closed | Extend via new implementations, not edits to stable logic |
| L | Liskov Substitution | Subtypes must honor the base contract |
| I | Interface Segregation | Split fat interfaces into role-specific ones |
| D | Dependency Inversion | Both policy and details depend on policy-owned abstractions |
Do it
S — Single Responsibility Principle (SRP)
Separate domain calculation from persistence or formatting so each changes for its own reason.
interface OrderLine {
priceCents: number;
qty: number;
}
class OrderCalculator {
totalCents(lines: OrderLine[]): number {
return lines.reduce((sum, l) => sum + l.priceCents * l.qty, 0);
}
}
class OrderReceiptFormatter {
format(totalCents: number): string {
return `Total: $${(totalCents / 100).toFixed(2)}`;
}
}O — Open/Closed Principle (OCP)
Add new discount rules by implementing DiscountPolicy instead of editing checkoutTotal.
interface DiscountPolicy {
apply(cents: number): number;
}
class NoDiscount implements DiscountPolicy {
apply(cents: number): number {
return cents;
}
}
class PercentDiscount implements DiscountPolicy {
constructor(private readonly percent: number) {}
apply(cents: number): number {
return Math.round(cents * (1 - this.percent / 100));
}
}
function checkoutTotal(cents: number, policy: DiscountPolicy): number {
return policy.apply(cents);
}L — Liskov Substitution Principle (LSP)
Any subtype passed where StorageReader is expected must return bytes or null — never surprise callers by throwing UnsupportedOperation on read.
interface StorageReader {
read(key: string): Promise<string | null>;
}
class MemoryReader implements StorageReader {
private readonly store = new Map<string, string>();
async read(key: string): Promise<string | null> {
return this.store.get(key) ?? null;
}
}I — Interface Segregation Principle (ISP)
Split a fat Worker interface so read-only consumers do not implement or mock write methods they never call.
interface ReadableRepo<T> {
findById(id: string): Promise<T | null>;
}
interface WritableRepo<T> {
save(item: T): Promise<void>;
}
// A reporting service only depends on ReadableRepo<Order>
class OrderReportService {
constructor(private readonly orders: ReadableRepo<{ id: string }>) {}
getOrder(id: string) {
return this.orders.findById(id);
}
}D — Dependency Inversion Principle (DIP)
High-level business logic owns the interface; infrastructure implements it. See Dependency Inversion in Practice for the full architectural boundary diagram and Bridge for how DIP powers the Bridge pattern.
// Domain owns the port
interface Clock {
now(): Date;
}
// Domain service depends only on Clock
class TokenService {
constructor(private readonly clock: Clock) {}
isExpired(expiresAt: Date): boolean {
return this.clock.now().getTime() > expiresAt.getTime();
}
}
// Infrastructure implements Clock
class SystemClock implements Clock {
now(): Date {
return new Date();
}
}Gotchas
- Over-splitting for SRP: Turning every single method into its own class creates indirection soup. Group things that change for the same business reason.
- Speculative OCP: Do not invent an abstraction layer for a single implementation that has no second variant in sight; refactor to an interface when the second variant arrives.
- Putting the interface in the infrastructure folder: That defeats DIP because the domain still imports from infrastructure.
Production checklist
- Business logic classes do not import database drivers, HTTP clients, or
Date.now()directly when testability matters. - Interfaces are small (1–3 methods) and named after what the caller needs.
- New variants (gateways, formatters, policies) are added as new implementations without editing core orchestration.
Check yourself
Check Yourself
1. A reporting module only reads orders, but its constructor takes a 10-method OrderStore interface that includes save, delete, and archive. Which principle does this violate?
2. Where should the interface live under the Dependency Inversion Principle?
Sources
Related Notes
OOP Pillars in TypeScript
Encapsulation, abstraction, inheritance, and polymorphism explained with practical TypeScript examples and modern composition trade-offs.
Composition vs Inheritance
Why deep inheritance creates fragile base classes, how has-a composition and TypeScript mixins compare, and when extends is still the right tool.