Patterns & principles · 10 of 10 · 21 min read
SOLID in TypeScript
The five principles where the compiler can actually check them — Liskov as variance, Interface Segregation as literally interfaces, and Dependency Inversion as a constructor parameter.
- Principles
SOLID was written for languages with interfaces, abstract classes and nominal types. TypeScript has all three, so unlike the JavaScript version of this lecture the principles map directly — and three of the five are enforced by the compiler rather than by discipline.
| Principle | The TypeScript mechanism | Checked? |
|---|---|---|
| Single Responsibility | small types, one reason to change | no — judgement |
| Open/Closed | a union plus exhaustive narrowing | yes |
| Liskov Substitution | override and assignability rules | yes |
| Interface Segregation | several small interfaces, intersected | partly |
| Dependency Inversion | depend on an interface, inject the implementation | partly |
S — Single Responsibility
For a type, the principle reads: one reason to change. A type that mixes concerns forces every consumer to depend on all of them.
// One type, four reasons to change: storage, API shape, UI state, auth.
interface UserEverything {
id: number;
name: string;
passwordHash: string;
isSelected: boolean;
lastQueryMs: number;
}
// Four types, each with one reason:
interface User { id: number; name: string }
interface Credentials { userId: number; passwordHash: string }
interface UserListItem extends User { isSelected: boolean }
interface QueryStats { lastQueryMs: number }
const item: UserListItem = { id: 1, name: "Ana", isSelected: false };
console.log(item.name);
The practical test is the one from the DRY lecture, inverted: if two fields never change for the
same reason, they probably do not belong in the same declaration. The symptom of getting this
wrong is an interface whose consumers all use a different third of it — and a passwordHash that
ends up in a JSON response because it was in the type that was convenient.
The same applies to classes, and TypeScript makes the fix cheap:
interface Validator { validate(email: string): boolean }
interface Mailer { send(to: string, body: string): Promise<void> }
interface Store { save(email: string): Promise<void> }
class Registration {
constructor(
private readonly validator: Validator,
private readonly store: Store,
private readonly mailer: Mailer,
) {}
async register(email: string): Promise<void> {
if (!this.validator.validate(email)) throw new Error("invalid email");
await this.store.save(email);
await this.mailer.send(email, "welcome");
}
}
console.log(typeof Registration);
Registration orchestrates and does nothing else. Each collaborator can change — a new mail
provider, a different store — without touching it.
O — Open for extension, closed for modification
The type-level version is the strongest form of this principle, because the compiler tells you every place that needs updating:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number }
| { kind: "triangle"; base: number; height: number }; // added
function area(shape: Shape): number {
switch (shape.kind) {
case "circle": return Math.PI * shape.radius ** 2;
case "square": return shape.side ** 2;
case "triangle": return (shape.base * shape.height) / 2;
default: {
const exhaustive: never = shape;
return exhaustive;
}
}
}
console.log(area({ kind: "triangle", base: 3, height: 4 })); // 6
Adding a member to Shape makes every non-exhaustive switch in the program a compile error, and
the never assignment is what produces the error. That is a different kind of guarantee from the
object-oriented version: the union is closed to new members arriving at runtime, and the
compiler finds every handler that has to grow.
The open-to-new-implementations version is the other half, and uses an interface instead:
interface Shape { area(): number }
class Circle implements Shape {
constructor(private readonly radius: number) {}
area() { return Math.PI * this.radius ** 2; }
}
class Triangle implements Shape {
constructor(private readonly base: number, private readonly height: number) {}
area() { return (this.base * this.height) / 2; }
}
function total(shapes: readonly Shape[]) {
return shapes.reduce((sum, shape) => sum + shape.area(), 0);
}
console.log(total([new Circle(1), new Triangle(3, 4)]).toFixed(2));
total never changes, and a new shape is a new file. Which of the two to use is a real decision:
a union when the set of cases is known and you want exhaustiveness; an interface when third-party
code should be able to add cases you have not seen.
L — Liskov Substitution
A subtype must be usable wherever the supertype is. In TypeScript this is not a guideline — it is the override check:
class Repository {
find(id: number | string): object | null { return null; }
}
class Narrowed extends Repository {
// find(id: number): object | null { return null; }
// Property 'find' in type 'Narrowed' is not assignable to the same property
// in base type 'Repository'.
// Accept more, return less — the rule, and it compiles:
override find(id: number | string | boolean): { ok: true } { return { ok: true }; }
}
console.log(new Narrowed().find("a"));
The compiler enforces the signature half. What it cannot check is the behavioural half, which is where the classic violations live:
class Rectangle {
constructor(public width: number, public height: number) {}
setWidth(value: number) { this.width = value; }
area() { return this.width * this.height; }
}
class Square extends Rectangle {
override setWidth(value: number) {
this.width = value;
this.height = value; // the signature is fine; the behaviour is a surprise
}
}
function resize(rectangle: Rectangle) {
rectangle.setWidth(5);
return rectangle.height; // a caller may reasonably expect this not to change
}
console.log(resize(new Rectangle(1, 2)), resize(new Square(1, 1))); // 2 5
Types cannot express “setting the width does not change the height”. The fix is not a better
signature but a better model: an immutable Shape with an area(), or two unrelated types. When
extends requires an override that surprises a caller, the inheritance was wrong.
Stronger preconditions are the other common violation, and also invisible to the type system:
class Validator {
validate(value: string): boolean { return value.length > 0; }
}
class StrictValidator extends Validator {
override validate(value: string): boolean {
if (value.length > 100) throw new Error("too long"); // a new precondition
return value.length > 0;
}
}
console.log(new Validator().validate("x"), new StrictValidator().validate("x"));
A caller holding a Validator does not expect a throw. A subtype may weaken what it demands and
strengthen what it promises — never the reverse.
I — Interface Segregation
The one principle whose name is literal in TypeScript, and the easiest to apply:
// A fat interface: every implementation must provide everything.
interface Machine {
print(document: string): void;
scan(): string;
fax(number: string): void;
}
// Segregated: intersect only what you have.
interface Printer { print(document: string): void }
interface Scanner { scan(): string }
interface Fax { fax(number: string): void }
class SimplePrinter implements Printer {
print(document: string) { console.log("printing", document); }
}
class OfficeMachine implements Printer, Scanner, Fax {
print(document: string) { console.log("printing", document); }
scan() { return "scanned"; }
fax(number: string) { console.log("faxing", number); }
}
// A consumer asks for exactly what it uses:
function printAll(printer: Printer, documents: readonly string[]) {
for (const document of documents) printer.print(document);
}
printAll(new SimplePrinter(), ["a"]);
printAll(new OfficeMachine(), ["b"]);
console.log(typeof (null as unknown as Machine));
Two compiler behaviours make this concrete. implements Machine on a printer that cannot scan is
an error, so the fat interface does not merely smell — it fails to compile or forces a
throw new Error("not supported") that every caller can hit. And because a class can implement
any number of interfaces, there is no cost to splitting them.
The parameter type is where the value lands: printAll(printer: Printer) accepts both classes,
and its test double is one method.
D — Dependency Inversion
Depend on an abstraction; let something else choose the implementation. The abstraction is an interface, and the injection is a constructor parameter:
// The interface is declared by the consumer, in the consumer's terms.
interface UserStore {
findByEmail(email: string): Promise<{ id: string } | null>;
save(user: { email: string }): Promise<{ id: string }>;
}
class RegisterUser {
constructor(private readonly store: UserStore) {}
async execute(email: string) {
if (await this.store.findByEmail(email)) throw new Error("taken");
return this.store.save({ email });
}
}
// Production supplies one implementation; a test supplies another.
const fake: UserStore = {
async findByEmail() { return null; },
async save(user) { return { id: `test-${user.email}` }; },
};
console.log((await new RegisterUser(fake).execute("a@b.c")).id);
The detail that makes this inversion rather than indirection: UserStore is defined by
RegisterUser, in the application’s language, and the database implementation conforms to it.
If the interface were declared next to the database and merely imported here, the dependency would
still point the wrong way.
TypeScript’s structural typing helps and hurts. It helps because an implementation needs no
implements clause to conform, so adapting a third-party client is nothing but a type annotation.
It hurts because nothing stops a module importing the concrete class directly — the compiler will
not report a layering violation. That part remains review and, if it matters, a lint rule on
import paths.
What is left to judgement
Three of the five are mechanised. The remaining judgement is worth stating plainly, because the principles are easy to over-apply:
- An interface with one implementation and no test double is indirection, not inversion. Add the seam when something uses it.
- Exhaustiveness is only a guarantee if the union is actually closed. A union that grows from a server response is a parsing problem first.
- Segregation has a floor. Six one-method interfaces for one class is as hard to read as one fat one. Split along the lines consumers actually use.
The YAGNI lecture’s test applies to all of it: a principle that is not currently preventing a bug is costing you a layer.
Common mistakes
implements on a class that cannot honour the interface
Mistake. class Printer implements Machine with scan() throwing.
Why it fails. Every consumer of Machine may call scan, and the type says they can. The
error moves from compile time to a user’s session.
What to do instead. Split the interface, and let the parameter type ask for the capability it
needs.
An override that strengthens a precondition
Mistake. A subclass that validates more strictly, or throws where the base returns. Why it fails. It is signature-compatible and behaviourally incompatible, so the compiler is silent and a caller holding the base type breaks. What to do instead. Make the stricter thing a separate type, or move the check to the caller that wants it.
An interface declared next to its implementation
Mistake. UserStore exported from the database module and imported by the use case.
Why it fails. The dependency still points from the application to the infrastructure — the
interface is a description of the database rather than a requirement of the application.
What to do instead. Declare the interface where it is consumed, in the consumer’s vocabulary,
and let the implementation conform to it.
Check yourself
4 questions from the bank on what you just read. Answering here does not affect your quiz history.
What does the Liskov Substitution principle look like in TypeScript?
What does Dependency Inversion look like when the abstraction is a TypeScript interface?
How does the Open/Closed principle look when the extension point is a type?
What does Single Responsibility mean for a type declaration?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.