×

typescript · level 2 · unit 5 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

guards data, and keeps a promise.

Properties are public by default, so any code can change them, even to nonsense, like a fridge holding minus three things. Mark one private and only the class's own methods can touch it. Code outside gets TS2341. The methods become the only doors in.

A class can also promise to match an interface: class Fridge implements Store. An interface can list methods too, with their parameters and return types. The checker then makes sure the class has every one.

interface Store { add(item: string): void; count(): number }
class Fridge implements Store {
  private items: string[] = [];
  add(item: string): void { this.items.push(item); }
  count(): number { return this.items.length; }
}
const fridge = new Fridge();
fridge.add("milk");
fridge.add("cheese");
console.log(`${fridge.count()} things in the fridge`);

A method this short can sit on one line, curly brackets and all.