π·
EPISODE 04
constructor Β· public/private Β· readonly Β· abstract
Classes in TypeScript
Use TypeScript's class features: access modifiers, parameter properties, readonly, and abstract classes for shared base behavior.
classconstructorprivatereadonlyabstract
Duration
β± About 1.5 hours
Level
π Intermediate
Prerequisite
π― ts-02
OUTCOME
Model real domain objects with class hierarchies
What you'll learn
- 1Use access modifiers (public, private, protected)
- 2Take advantage of parameter properties
- 3Mark immutable fields with readonly
- 4Define abstract base classes
1. Basic Class
typescript
class BankAccount {
private balance: number = 0;
constructor(public readonly owner: string) {}
deposit(amount: number): void {
if (amount <= 0) throw new Error("amount must be positive");
this.balance += amount;
}
getBalance(): number {
return this.balance;
}
}
const acct = new BankAccount("Alice");
acct.deposit(100);
// acct.balance = 0; // error: privatepublic readonly owner: string is a parameter property β it both accepts the arg and assigns this.owner in one place.
2. Inheritance & abstract
typescript
abstract class Shape {
abstract area(): number;
describe(): string { return `area=${this.area()}`; }
}
class Circle extends Shape {
constructor(private r: number) { super(); }
area() { return Math.PI * this.r ** 2; }
}
class Rect extends Shape {
constructor(private w: number, private h: number) { super(); }
area() { return this.w * this.h; }
}
const shapes: Shape[] = [new Circle(5), new Rect(3, 4)];
shapes.forEach(s => console.log(s.describe()));3. implements an Interface
typescript
interface Serializable { toJSON(): string }
class Note implements Serializable {
constructor(public title: string, public body: string) {}
toJSON() { return JSON.stringify(this); }
}Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub β