Classes and access modifiers

Intermediate · 32 min

What TypeScript adds to JavaScript classes: field declarations, public/private/protected, private vs #private, parameter properties, and override.

Before thisObject types, optional and readonly propertiesStrict mode and the compiler flags that matter

Dave Gray · 32 min

Classes and access modifiers

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Dave GrayReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • TypeScript requires every class field to be declared with its type, and under `strictPropertyInitialization` each one must be initialised, marked optional, or given a definite assignment assertion `!`.
  • `public` is the default, `private` limits a member to its own class, `protected` also allows subclasses, and `readonly` blocks reassignment after construction.
  • TypeScript's `private` is checked only at compile time and erased from the output, so the value is still an ordinary property at runtime; JavaScript's `#private` fields are enforced by the engine itself.
  • Bracket access like `obj["secret"]` deliberately skips the `private` check, which is one more reason to prefer `#private` when the privacy really matters.
  • A parameter property such as `constructor(private email: string)` declares and assigns a field in one step, but it generates code, so `erasableSyntaxOnly` reports it as an error.
  • The `override` modifier marks a method that replaces one in the base class, and `noImplicitOverride` makes it mandatory, so renaming a base method can't silently orphan a subclass's version.

Classes are JavaScript; the checks are TypeScript

A class in TypeScript is a JavaScript class. Constructors, extends, super, static members and #private fields all behave exactly as they do in plain JavaScript, and the JavaScript roadmap covers those mechanics. TypeScript adds a layer on top: it wants to know what fields an instance has and who is allowed to touch them. Most of that layer is erased when you compile. A few pieces aren’t, and knowing which is which matters.

Fields have to be declared

In JavaScript you can assign this.owner anywhere and the property springs into existence. TypeScript needs the shape up front, so instance fields are declared in the class body:

class Account {
  owner: string;
  balance = 0;
  nickname?: string;
  ledgerId!: string; // set later by connect(), so we promise it's there

  constructor(owner: string) {
    this.owner = owner;
  }
}

class Broken {
  name: string; // Error: Property 'name' has no initializer and is not definitely assigned in the constructor.
}

That error comes from strictPropertyInitialization, part of strict. Without it, name would be typed string while actually being undefined. Each field in Account shows one way to satisfy the check: assign it in the constructor, give it an initialiser, make it optional, or use ! to assert that something else assigns it before anyone reads it. The ! is a promise the compiler can’t verify, so keep it for cases like framework lifecycle hooks where you know the order.

public, private, protected, readonly

Access modifiers say who may use a member:

class BankAccount {
  public readonly id: string;
  private balance = 0;
  protected history: number[] = [];

  constructor(id: string) {
    this.id = id;
  }

  deposit(amount: number) {
    this.balance += amount;
    this.history.push(amount);
  }
}

class SavingsAccount extends BankAccount {
  addInterest(rate: number) {
    const deposited = this.history.reduce((sum, n) => sum + n, 0); // fine: protected
    this.deposit(deposited * rate); // fine: public
    this.balance = 0; // Error: Property 'balance' is private and only accessible within class 'BankAccount'.
  }
}

const acct = new BankAccount("acc-1");
acct.deposit(50);
acct.balance; // Error: Property 'balance' is private and only accessible within class 'BankAccount'.
acct.history; // Error: Property 'history' is protected and only accessible within class 'BankAccount' and its subclasses.
acct.id = "acc-2"; // Error: Cannot assign to 'id' because it is a read-only property.

public is the default and rarely needs writing. private means this class only. protected widens that to subclasses. readonly can be combined with any of them and allows assignment only in the declaration or the constructor.

private versus #private

Here is the part that trips people up. TypeScript’s private is a type-checker rule, and the type checker disappears at runtime:

class Session {
  private token = "abc123";
  #signingKey = "k-9f2";

  sign(payload: string) {
    return `${payload}.${this.#signingKey}`;
  }
}

const s = new Session();
s["token"]; // compiles: bracket access skips the private check
JSON.stringify(s); // '{"token":"abc123"}' at runtime
s.#signingKey; // Error: Property '#signingKey' is not accessible outside class 'Session' because it has a private identifier.

Think of private as a “staff only” sign on an unlocked door. Everyone who reads the sign stays out, but the door opens for anyone who ignores it: plain JavaScript callers, a cast to any, bracket access, JSON.stringify, Object.keys. A # field is a locked door. The engine itself refuses access from outside the class, and the field doesn’t show up as a property at all. The JavaScript lesson on private fields covers how that works.

So which to use? private is fine for “please don’t depend on this” inside your own codebase, and it reads more familiarly to people coming from Java or C#. Use #private when the value must not leak: secrets, internal state a library’s users shouldn’t reach, anything you’d regret seeing in a serialised log.

Parameter properties

A constructor that just copies its arguments onto this is so common that TypeScript has a shorthand. Put a modifier on a constructor parameter and it becomes a field:

class User {
  constructor(
    public readonly id: string,
    private email: string,
  ) {}

  domain() {
    return this.email.split("@")[1];
  }
}

const u = new User("u1", "ada@example.com");
u.id; // "u1"

This is one of the few TypeScript features that produces code: the compiler has to write this.id = id for you. That means it isn’t erasable. If you run TypeScript through Node’s type stripping and turn on erasableSyntaxOnly, both parameters above are reported with “This syntax is not allowed when ‘erasableSyntaxOnly’ is enabled.” In that setup, declare the fields and assign them by hand.

override and noImplicitOverride

Subclasses replace base-class methods all the time. The risk is drift: someone renames the base method, and the subclass’s version quietly becomes a separate method nobody calls. The override modifier tells the compiler “this must replace something”:

class Shape {
  area(): number {
    return 0;
  }
  describe() {
    return `area: ${this.area()}`;
  }
}

class Square extends Shape {
  constructor(private side: number) {
    super();
  }
  override area() {
    return this.side ** 2;
  }
  override perimeter() { // Error: This member cannot have an 'override' modifier because it is not declared in the base class 'Shape'.
    return this.side * 4;
  }
}

class Circle extends Shape {
  constructor(private radius: number) {
    super();
  }
  area() { // Error (with noImplicitOverride): This member must have an 'override' modifier because it overrides a member in the base class 'Shape'.
    return Math.PI * this.radius ** 2;
  }
}

On its own, override is opt-in. Turn on noImplicitOverride and it becomes required, which closes the loop: every replacement is marked, and every mark is checked. It isn’t part of strict, so add it to your tsconfig yourself.

About the video

Dave Gray’s video walks through the TypeScript side of classes in order: visibility modifiers and readonly, the parameter-property shorthand (around 04:23), the definite assignment assertion (06:24), and a look at the compiled JavaScript to see what gets erased (10:26). It then moves on to extends, implements, static members, and getters and setters. The implements part previews the next lesson. The video doesn’t compare private with #private or cover override, which is why those sections above are the longest.

Check yourself

  1. 01Why does `class Broken { name: string; }` fail under `strict`, and what are three ways to fix it?

    `strictPropertyInitialization` requires every declared field to be definitely assigned by the end of the constructor, and nothing assigns `name`. You can initialise it (`name = ""`), assign it in the constructor, mark it optional (`name?: string`), or, if something else sets it before use, add a definite assignment assertion (`name!: string`).

  2. 02A class has `private token = "abc"`. Can code outside the class read the token at runtime, and why?

    Yes. `private` is a compile-time check that is erased when TypeScript emits JavaScript, so `token` ends up as a normal property. It shows up in `JSON.stringify`, `Object.keys`, the debugger, and through `obj["token"]` or a cast to `any`. A `#token` field would not be reachable from outside the class at all.

  3. 03What is the difference between `private` and `protected`?

    A `private` member can only be used inside the class that declares it. A `protected` member can also be used inside subclasses, but neither can be used from outside the class hierarchy, for example on an instance in calling code.

  4. 04What does `constructor(public readonly id: string) {}` do, and why does `erasableSyntaxOnly` reject it?

    It declares a public read-only field `id` and assigns the constructor argument to it, with no separate declaration or `this.id = id` line. Because the assignment has to be generated as JavaScript rather than simply removed, it isn't erasable syntax, and type-stripping runtimes like Node can't run it.

  5. 05With `noImplicitOverride` on, a base class renames `area()` to `getArea()`. What happens to a subclass that declared `override area()`?

    It stops compiling: TypeScript reports that `area` can't have an `override` modifier because the base class no longer declares it. Without `override`, the subclass's `area` would silently become a new, unrelated method, and code calling `getArea()` would get the base version.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark