Classes in TypeScript
Typed classes, access modifiers, constructors, abstract classes, and implements
Skills taught: ts.class-types, ts.access-modifiers, ts.readonly-class, ts.abstract-class, ts.implements
Typed class with access modifiers
class BankAccount {
readonly id: number; // set once in constructor
private balance: number; // only this class can access
protected owner: string; // this class and subclasses
public currency: string; // anyone can access
constructor(id: number, owner: string, initialBalance: number) {
this.id = id;
this.owner = owner;
this.balance = initialBalance;
this.currency = 'INR';
}
// Public method — part of the API
deposit(amount: number): void {
if (amount <= 0) throw new Error('Amount must be positive');
this.balance += amount;
}
withdraw(amount: number): void {
if (amount > this.balance) throw new Error('Insufficient funds');
this.balance -= amount;
}
getBalance(): number {
return this.balance; // controlled access to private field
}
}
const account = new BankAccount(1, 'Alice', 1000);
account.deposit(500);
account.withdraw(200);
console.log(account.getBalance()); // 1300
// account.balance; // Error: private
// account.id = 2; // Error: readonly
// Parameter property shorthand — same as above but shorter
class Point {
constructor(
public readonly x: number,
public readonly y: number
) {}
distanceTo(other: Point): number {
return Math.hypot(this.x - other.x, this.y - other.y);
}
}
const p1 = new Point(0, 0);
const p2 = new Point(3, 4);
console.log(p1.distanceTo(p2)); // 5
Abstract classes and implements
// Interface — the contract
interface Serializable {
serialize(): string;
toJSON(): object;
}
// Abstract class — partial implementation
abstract class Shape implements Serializable {
constructor(public readonly color: string) {}
abstract area(): number; // subclass MUST implement
abstract perimeter(): number;
// Concrete method — available in all subclasses
describe(): string {
return `A ${this.color} shape with area ${this.area().toFixed(2)}`;
}
serialize(): string {
return JSON.stringify(this.toJSON());
}
}
class Circle extends Shape {
constructor(color: string, public readonly radius: number) {
super(color);
}
area(): number { return Math.PI * this.radius ** 2; }
perimeter(): number { return 2 * Math.PI * this.radius; }
toJSON(): object {
return { type: 'circle', radius: this.radius, color: this.color };
}
}
class Rectangle extends Shape {
constructor(
color: string,
public readonly width: number,
public readonly height: number
) { super(color); }
area(): number { return this.width * this.height; }
perimeter(): number { return 2 * (this.width + this.height); }
toJSON(): object {
return { type: 'rectangle', width: this.width, height: this.height, color: this.color };
}
}
const c = new Circle('red', 5);
const r = new Rectangle('blue', 4, 6);
console.log(c.describe());
console.log(r.describe());
console.log(c.serialize());
// const s = new Shape('green'); // Error: Cannot instantiate abstract class
Frequently Asked Questions
Are TypeScript's private fields actually private at runtime?
No — TypeScript's private modifier is only enforced at compile time. The compiled JavaScript has no access control. For true runtime privacy, use JavaScript's native # private fields: class C { #secret = 'hidden'; }. These use WeakMap-based storage and are truly inaccessible from outside the class. TypeScript supports # fields and enforces them at both compile and runtime.