Skip to content
dreamcode
dreamcode
Map
Classes
Lesson 12 of 26
+15 XP on finish
TYPESCRIPTChapter 2 · TS Unions & Enums

Classes and visibility modifiers

TypeScript classes extend JavaScript classes by adding types and visibility modifiers: public (accessible anywhere), private (accessible only inside the class), and protected (accessible inside the class and its subclasses).

Worked example

How it reads

  • private altitude prevents external access to this property
  • public name allows normal reading and writing from outside
Cloud tip: You can declare class properties directly in the constructor parameters as public/private as a shorthand.
index.ts
TYPESCRIPT
type-checked, then run in your browser
Console
Run your code to see its output here.
YOUR TURN

Add a public method addCrew(n: number) that increases the private crew and returns the new count. Log ship.addCrew(2): 5.

Press Run to check your work.