Classes in TypeScript
Classes model state and behavior with rich typing: fields, modifiers, inheritance, and interfaces.
Fields and constructors
class Point {
x: number;
y: number;
constructor(x: number, y: number) { this.x = x; this.y = y; }
move(dx: number, dy: number) { this.x += dx; this.y += dy; }
}
Parameter properties and readonly
class User {
constructor(public readonly id: number, public name: string) {}
}
Shorthand for declaring and initializing fields from constructor params.
Access modifiers
- public (default)
- private (class‑private)
- protected (visible to subclasses)
#private(runtime private fields, JS syntax)
class C { #secret = 1; private legacy = 2; }
Implements and extends
interface Drivable { drive(km: number): void }
class Car implements Drivable { drive(km: number) { /* ... */ } }
abstract class Shape { abstract area(): number }
class Circle extends Shape {
constructor(public r: number) { super(); }
area() { return Math.PI * this.r ** 2 }
}
this and polymorphic this
class Builder {
setName(name: string): this { return this; }
setAge(age: number): this { return this; }
}
class PersonBuilder extends Builder {}
const pb = new PersonBuilder().setName("Ada").setAge(30); // fluent API
Static members
class Id {
static next = 1;
static make() { return this.next++; }
}
Summary
- Prefer
readonlyand parameter properties for concise, safe classes - Use interfaces for contracts; abstract classes for shared behavior and state