CPCODELAB
TypeScript

Classes with Types & Access Modifiers

12 min read

Classes with Types & Access Modifiers

TypeScript extends JavaScript classes with access modifiers and strict property typing. Class members can be public (default), private, or protected. TypeScript 4.3+ also supports the native # private field syntax.

ts
class BankAccount {
  private balance: number;
  readonly accountNumber: string;

  constructor(accountNumber: string, initialBalance: number = 0) {
    this.accountNumber = accountNumber;
    this.balance = initialBalance;
  }

  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;
  }
}

Parameter properties

TypeScript provides a shorthand to declare and initialise class properties directly in the constructor signature.

ts
// Longhand
class Point {
  public x: number;
  public y: number;
  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }
}

// Shorthand (parameter properties)
class Point2 {
  constructor(public x: number, public y: number) {}
}

Implementing interfaces

ts
interface Serializable {
  serialize(): string;
  deserialize(data: string): void;
}

class JsonModel implements Serializable {
  private data: Record<string, unknown> = {};

  serialize(): string {
    return JSON.stringify(this.data);
  }

  deserialize(raw: string): void {
    this.data = JSON.parse(raw) as Record<string, unknown>;
  }
}

TypeScript's private keyword is a compile-time check only — the property is still accessible at runtime in JavaScript. Use the # native private field syntax if you need true runtime privacy.

Ready to test yourself?
Practice TypeScript— quiz & coding exercises