TypeScript by Example

Classes

Constructor parameter shorthand, access modifiers, readonly fields, and abstract classes.

TypeScript adds type-level access modifiers to JavaScript classes. Constructor shorthand keeps field declarations and initialization together.

Prefix a constructor parameter with public, private, protected, or readonly and TypeScript creates the field.

class User {
  constructor(
    public readonly id: string,
    public name: string,
    private email: string,
    protected role: string = "member",
  ) {}
 
  describe(): string {
    return `${this.name} (${this.role}) <${this.email}>`;
  }
}
 
const user = new User("u-1", "Ada", "ada@example.com");
console.log(user.id);
// user.email; // TypeScript error

Abstract classes define shared behavior plus methods subclasses must implement.

abstract class Shape {
  abstract area(): number;
 
  describe(): string {
    return `area=${this.area().toFixed(2)}`;
  }
}
 
class Circle extends Shape {
  constructor(private radius: number) {
    super();
  }
  area(): number {
    return Math.PI * this.radius ** 2;
  }
}

In production

TypeScript access modifiers protect the type boundary, not runtime secrets. They are still useful for internal APIs, but use JavaScript #private fields when runtime privacy matters.

Enjoyed this? Get more software craft delivered to your inbox.