OOP Pillars in TypeScript
Encapsulation, abstraction, inheritance, and polymorphism explained with practical TypeScript examples and modern composition trade-offs.
TL;DR
Object-oriented design rests on four pillars: encapsulation (protect invariants), abstraction (hide details behind a contract), inheritance (reuse via an is-a hierarchy), and polymorphism (swap implementations behind one interface). In TypeScript, prefer interfaces and composition over deep class trees.
Why it exists
Without clear boundaries around state and behavior, business rules leak across callers: any function can mutate an object's fields into an invalid state, and adding a new variant forces if/else chains everywhere.
Mental model
Think of the four pillars as tools for controlling change:
- Encapsulation — keep mutable state private so only validated methods can change it.
- Abstraction — let callers depend on what an object does (
interface) rather than how it does it. - Inheritance — share structure and behavior down an
is-ahierarchy (extends). - Polymorphism — write one caller that works with any implementation matching the contract.
Do it
1. Encapsulation
Use private (or # private fields) to guard invariants instead of exposing raw mutable fields.
class BankAccount {
#balanceCents = 0;
deposit(cents: number): void {
if (cents <= 0) throw new Error('Deposit must be positive');
this.#balanceCents += cents;
}
get balanceCents(): number {
return this.#balanceCents;
}
}2. Abstraction & 3. Polymorphism
Define a minimal interface, then pass any conforming implementation to the caller.
interface Notifier {
send(to: string, message: string): Promise<void>;
}
class EmailNotifier implements Notifier {
async send(to: string, message: string): Promise<void> {
console.log(`Email -> ${to}: ${message}`);
}
}
class SlackNotifier implements Notifier {
async send(to: string, message: string): Promise<void> {
console.log(`Slack -> ${to}: ${message}`);
}
}
// Polymorphic caller: works with any Notifier without branching
async function notifyUser(notifier: Notifier, user: string): Promise<void> {
await notifier.send(user, 'Deployment finished');
}4. Inheritance (use sparingly)
extends models an is-a relationship. Keep hierarchies shallow (1–2 levels) and prefer composition when dimensions vary independently.
abstract class RetryableJob {
constructor(protected readonly maxAttempts: number) {}
protected abstract execute(): Promise<void>;
async run(): Promise<void> {
for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {
try {
await this.execute();
return;
} catch (err) {
if (attempt === this.maxAttempts) throw err;
}
}
}
}
class SyncUsersJob extends RetryableJob {
protected async execute(): Promise<void> {
// perform sync
}
}Gotchas
- TypeScript
privatevs JS#field: TypeScript'sprivateis compile-time only and disappears in emitted JS. Use#fieldwhen you need runtime privacy. - Inheritance for code reuse alone: Subclassing just to borrow a helper method couples the child to every parent change. Extract a plain function or compose a collaborator instead (see Bridge).
- Structural typing surprises: TypeScript checks shapes, not class names — two unrelated classes with identical public members are assignable to each other unless they have
privateor#fields.
Production checklist
- Keep class fields private (
#orprivate readonly) and validate state transitions in methods. - Depend on small
interfacecontracts at module boundaries rather than concrete classes. - Reach for composition before
extendswhenever behavior varies along more than one axis.
Check yourself
Check Yourself
1. What is the main difference between TypeScript's private keyword and ECMAScript #private fields?
2. In the notifyUser(notifier: Notifier, user: string) example, which OOP pillar lets notifyUser work with both EmailNotifier and SlackNotifier without an if/else check?
Sources
Related Notes
Argo CD vs Flux: Picking a GitOps Controller
Compare Argo CD and Flux CD across architecture, web UI, multi-tenancy, Helm/Kustomize support, and team fit.
SOLID Principles in TypeScript
The five SOLID object-oriented design principles with concise TypeScript examples and links to Bridge and Dependency Inversion.