Lesson 8 of 11 · 11 min

Classes and access modifiers

TypeScript adds a few useful keywords to JavaScript classes:

class Account {
  readonly owner: string;
  private balance = 0;

  constructor(owner: string) {
    this.owner = owner;
  }

  deposit(amount: number): void {
    this.balance += amount;
  }

  getBalance(): number {
    return this.balance;
  }
}

const a = new Account("Ana");
a.deposit(50);
a.balance = 1000000;   // error: 'balance' is private
a.owner = "Tino";      // error: 'owner' is read-only
Modifier Who can use it
public (the default) anyone
private only code inside this class
protected this class and classes that extend it
readonly set once, never changed

Hiding state behind methods means the class controls every change, so it can keep its data valid.

implements

A class can promise to match an interface. TypeScript then checks it has everything the interface requires:

interface Shape { area(): number }

class Square implements Shape {
  constructor(private side: number) {}
  area() { return this.side * this.side; }
}

(private side in the constructor is a shortcut: it declares and sets the field in one go.)

Classes can be generic too: class Box<T> { constructor(public value: T) {} }.

Your task

Write class Stack<T> that implements the Collection<T> interface in the starter. Keep the items in a private array. Then fix the code at the bottom so it uses the stack's methods instead of reaching into its items.

main.ts
interface Collection<T> {
  push(item: T): void;
  pop(): T | undefined;
  peek(): T | undefined;
  size(): number;
}

class Stack {
  items = [];
}

const plates = new Stack();
plates.items.push("blue");
console.log(plates.items.length);

TypeScript 5.9 runs right here in your browser. The first run downloads about 1.5 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…