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.
TL;DR
Inheritance (is-a) couples subclasses to a parent's internal implementation and multiplies classes when dimensions vary independently (fragile base class). Composition (has-a) delegates to small interfaces you can swap at runtime. Keep extends shallow (custom Error types, one-level base contracts) and reach for composition everywhere else.
Why it exists
Inheritance looks like the quickest way to reuse code: class CachedS3Store extends S3Store. Two months later, S3Store changes how put() calls putBatch(), and CachedS3Store double-counts or skips cache invalidation. Meanwhile, you also need CachedGcsStore and RetryingS3Store, and JavaScript/TypeScript only allows single inheritance.
Mental model
| Approach | Relationship | Coupling | Runtime swappable? | Best for |
|---|---|---|---|---|
Inheritance (extends) | is-a | Tight (shares protected state & call order) | No | Shallow 1-level Errors or strict subtype hierarchies |
| TypeScript Mixin | is-a (composed prototype) | Medium (name collisions possible) | No | Framework-level cross-cutting traits when extends is required |
Composition (has-a) | has-a | Loose (depends on interface only) | Yes | Swappable drivers, strategies, decorators, test fakes |
Do it
1. The fragile base class problem
When a base class calls one of its own public/protected methods internally, changing that internal call breaks subclasses that overrode the method:
class BaseMetrics {
protected count = 0;
increment(): void {
this.count += 1;
}
incrementBatch(n: number): void {
// Refactoring this to call `this.increment()` n times
// breaks any subclass that overrides `increment()` and also calls `super.incrementBatch()`.
this.count += n;
}
}2. Prefer has-a composition
Give the class a collaborator behind a small interface instead of subclassing:
interface RetryPolicy {
run<T>(op: () => Promise<T>): Promise<T>;
}
class FixedRetry implements RetryPolicy {
constructor(private readonly maxAttempts: number) {}
async run<T>(op: () => Promise<T>): Promise<T> {
let lastErr: unknown;
for (let i = 0; i < this.maxAttempts; i++) {
try {
return await op();
} catch (err) {
lastErr = err;
}
}
throw lastErr;
}
}
// HealthChecker HAS-A RetryPolicy (not IS-A Retryable)
class HealthChecker {
constructor(private readonly retry: RetryPolicy) {}
check(url: string): Promise<boolean> {
return this.retry.run(async () => url.startsWith('https://'));
}
}3. TypeScript mixins vs composition
TypeScript supports class-expression mixins (function WithTimestamps<TBase extends Constructor>(Base: TBase)), which attach extra properties onto a subclass. Mixins are useful when a framework requires a single class prototype, but they still share one this namespace (risking silent property collisions) and are harder to type-check than injecting a Clock or Logger field. Prefer composition in application code.
4. When inheritance IS fine
- Custom
Errorsubclasses:class ConfigError extends Erroris a genuineis-arelationship that preservesinstanceofand stack traces. - Shallow (1-level) Template Method: an abstract base class with one
protected abstract execute()hook where subclasses never override concrete parent methods.
When NOT to use it
Overengineering happens when you outlaw extends Dogmatically and wrap a 5-line class ConfigError extends Error in a ConfigErrorWrapper composition object. Equally, overusing composition by creating ten 1-method interfaces for helpers that never vary just adds indirection—plain functions are often better than both classes and mixins.
Real-world example in this stack
This codebase uses composition everywhere: React components compose <Flow>, <Diagram>, <Quiz>, and <Checklist> rather than inheriting from a base DocPage class, and Bridge and Decorator show how has-a delegation replaces M × N class trees.
Gotchas
- TypeScript structural typing hides
is-amistakes: Two unrelated classes with the same public fields are assignable to each other unless they haveprivateor#fields. - Liskov Substitution Principle (LSP) violations: If your subclass throws
NotImplementedErroron an inherited method (e.g.ReadOnlyCache extends Cache), it is not a trueis-asubtype—split the interface and compose instead. - Mixin type complexity: Complex generic mixins often trigger cryptic
TS2545: A mixin class must have a constructor with a single rest parametererrors.
Production checklist
- Keep inheritance trees at most 1–2 levels deep (
Base -> Concrete). - Use
has-acomposition whenever you want to swap behavior in tests or at runtime. - Never subclass just to borrow utility methods—extract a plain module function instead.
Check yourself
Check Yourself
1. Why can changing a seemingly internal implementation detail in a base class break subclasses?
2. When is class inheritance (extends) still a good choice in TypeScript?
Sources
- TypeScript Handbook: Classes
- TypeScript Handbook: Mixins
- Dive Into Design Patterns (Alexander Shvets), chapter "Software Design Principles: Favor Composition Over Inheritance"
Related Notes
SOLID Principles in TypeScript
The five SOLID object-oriented design principles with concise TypeScript examples and links to Bridge and Dependency Inversion.
Dependency Injection in TypeScript
Constructor injection by hand vs DI containers, testing with in-memory fakes, why Service Locator is an anti-pattern, and when DI is overkill.