TypeScriptLesson 10 of 16

Classes and access modifiers

A TypeScript class is a JavaScript class with types and access modifiers. The modifiers decide who may read and change each field.

Key points

  • public is the default: everyone can use the field.
  • private works only inside the class; protected also allows subclasses.
  • readonly is set once, usually in the constructor.
  • constructor(public readonly label: string) declares and fills a field in one line.
  • private is checked only by the compiler; real JavaScript privacy uses # fields.

Example

interface Resettable {  reset(): void;} class Counter implements Resettable {  private count = 0;   // "public readonly label" declares and fills a property in one go  constructor(public readonly label: string) {}   increment(): void {    this.count++;  }   reset(): void {    this.count = 0;  }   get value(): number {    return this.count;  }} const clicks = new Counter("clicks");clicks.increment();clicks.increment();// clicks.count = 10;     // error: 'count' is private// clicks.label = "taps"; // error: 'label' is read-only console.log(`${clicks.label}: ${clicks.value}`);clicks.reset();console.log(`after reset: ${clicks.value}`);

From outside you can change neither count nor label, so both error lines are commented out. The value is read through the value getter, and implements checks that reset exists.

Task

How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.

Make balance private, add a withdraw method that never takes the balance below zero, and a total getter. Output: "Withdraw 20: true", "Withdraw 40: false", "Mia has 30".

Output

What your program prints appears here.