Skip to Content
Mengty Learns
Design

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.

explanationintermediateTested with typescript 7.0.2Updated Nov 26, 2026

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

ApproachRelationshipCouplingRuntime swappable?Best for
Inheritance (extends)is-aTight (shares protected state & call order)NoShallow 1-level Errors or strict subtype hierarchies
TypeScript Mixinis-a (composed prototype)Medium (name collisions possible)NoFramework-level cross-cutting traits when extends is required
Composition (has-a)has-aLoose (depends on interface only)YesSwappable 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 Error subclasses: class ConfigError extends Error is a genuine is-a relationship that preserves instanceof and 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-a mistakes: Two unrelated classes with the same public fields are assignable to each other unless they have private or # fields.
  • Liskov Substitution Principle (LSP) violations: If your subclass throws NotImplementedError on an inherited method (e.g. ReadOnlyCache extends Cache), it is not a true is-a subtype—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 parameter errors.

Production checklist

  • Keep inheritance trees at most 1–2 levels deep (Base -> Concrete).
  • Use has-a composition 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