1. Concept library
  2. JavaScript & TypeScript
  3. Module 9: Classes and composition

Concept

Class fields and access modifiers

Classes declare their fields with types, and private, protected and public say who may touch them. TypeScript checks the modifiers at compile time; #private fields are enforced at runtime too.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what private, protected and public check and when that check happens
  2. Write a class with typed fields and a constructor that initialises them
  3. Explain how #private fields differ from the private keyword at runtime

In practice

A few lines that show Class fields and access modifiers doing its job.

TypeScript
class Counter {
  #count = 0;
  readonly name: string;

  constructor(name: string, private readonly step = 1) {
    this.name = name;
  }

  increment(): number {
    this.#count += this.step;
    return this.#count;
  }
}

The common mistake

Watch for

Relying on private to hide data from untrusted code. The TypeScript keyword is erased when compiled, and the field is a normal property at runtime. Use #fields when it must hold.

What to know first

Your roadmap puts these before Class fields and access modifiers, unless you already know them.

How it stays learned

Once a session shows you understand Class fields and access modifiers, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on Class fields and access modifiers.

Next in the moduleImplementing interfaces →