typescript · level 2 · unit 5 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Reaching into a private box. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Scoreboard {
private points: number = 0;
win(): void { this.points = this.points + 3; }
total(): number { return this.points; }
}
const board = new Scoreboard();
board.win();
board.points = 100;
console.log(board.total());
your turn
Your turn. Keep a promise about shapes.
The Square class promises to be a Shape. Give the side a length, then finish area so it multiplies the side by itself.
fix it
The cat broke its promise. Fix it!
- Read the error:
TS2420: Class 'Cat' incorrectly implements interface 'Pet'.Something the interface lists is missing. - The interface on line 1 promises a method called speak. Look closely at the method name on line 4.
- Change
speektospeakon line 4, then press run.
nailed it
your classes guard their own data. :D
- Only a class's own methods can touch a
privateproperty. - Methods become the safe way in and out.
implementsmakes a class keep an interface's promise.
new words in your collection
- private
- implements
This lesson isn’t saved. A free account remembers every lesson you finish.