← TypeScript

Intermediate · 12 of 16 · 16 min read

Classes and access modifiers

What TypeScript adds to a JavaScript class — modifiers that vanish at compile time, parameter properties, abstract, and the field-initialisation check.

  • Access modifiers

A TypeScript class is a JavaScript class with types on the members, plus four things the language does not have: access modifiers, parameter properties, abstract, and a check that every declared field is actually assigned.

private versus #private

class Account {
  private tsPrivate = 1;
  #jsPrivate = 2;

  compare() { return [this.tsPrivate, this.#jsPrivate]; }
}

const account = new Account();
// account.tsPrivate;  // Property 'tsPrivate' is private
// account.#jsPrivate; // Property '#jsPrivate' is not accessible

console.log((account as any).tsPrivate); // 1 — still there at runtime
console.log(Object.keys(account));        // ["tsPrivate"] — and enumerable
console.log(JSON.stringify(account));     // {"tsPrivate":1}
console.log(account.compare());

The as any line is the whole difference. private is a promise between you and the compiler; # is a promise the runtime keeps. There is one place private is stronger: it makes the class nominal for assignability, so a plain object can no longer stand in for it.

class Open { constructor(public name: string) {} }
const a: Open = { name: "Ana" };   // a plain object satisfies it

class Closed {
  private brand = true;
  constructor(public name: string) {}
}
// const b: Closed = { name: "Ana", brand: true };
// Types have separate declarations of a private property 'brand'
console.log(a.name);
private protected public #name
Inside the class yes yes yes yes
In a subclass no yes yes no
Outside no no yes no
Survives compilation yes, readable yes, readable yes no — truly private
Enforced at runtime no no n/a yes
In Object.keys / JSON yes yes yes no
class Base {
  private secret = "hidden";
  protected shared = "inherited";
  reveal() { return this.secret; }
}

class Derived extends Base {
  show() {
    // return this.secret; // private — only within Base
    return this.shared;    // protected — fine here
  }
}

const d = new Derived();
console.log(d.show(), d.reveal()); // "inherited" "hidden"

Parameter properties

A modifier on a constructor parameter declares the field and assigns it:

class Short {
  constructor(
    private key: string,
    public readonly id: number,
  ) {}

  describe() { return `${this.id}:${this.key}`; }
}

class Long {
  private key: string;
  public readonly id: number;
  constructor(key: string, id: number) {
    this.key = key;
    this.id = id;
  }
}

console.log(new Short("k", 1).describe(), new Long("k", 1).id);

Any of public, private, protected or readonly triggers it. Without one the parameter stays an ordinary argument and is gone when the constructor returns. It is TypeScript-only syntax, which is worth knowing: a tool that only strips types has to understand it specially, and some do not.

readonly

class Config {
  readonly host: string;
  readonly tags: string[] = [];

  constructor(host: string) {
    this.host = host;   // assignment in the constructor is allowed
  }
}

const c = new Config("localhost");
// c.host = "other";  // Cannot assign to 'host'
c.tags.push("a");      // allowed — the array itself is not readonly
console.log(c.host, c.tags);

One level, compile-time only, and assignable from inside the constructor. For a class whose instances should be genuinely immutable, readonly on every member plus readonly array types is the declaration; Object.freeze is the runtime half.

static

class Counter {
  static #total = 0;
  static readonly MAX = 100;

  static {
    console.log("Counter ready"); // a static initialisation block
  }

  constructor() { Counter.#total += 1; }
  static get total() { return Counter.#total; }
}

new Counter();
new Counter();
console.log(Counter.total, Counter.MAX); // 2 100

// The class itself has a type:
function describe(cls: typeof Counter) { return cls.MAX; }
console.log(describe(Counter));

typeof Counter is the type of the class value — the thing with the statics on it — as opposed to Counter, which is the instance type. That distinction matters whenever a function takes a class as an argument.

abstract

abstract class Shape {
  constructor(public name: string) {}

  abstract area(): number;          // subclasses must provide this

  describe(): string {              // shared implementation
    return `${this.name}: ${this.area()}`;
  }
}

class Square extends Shape {
  constructor(private side: number) { super("square"); }
  area() { return this.side ** 2; }
}

console.log(new Square(3).describe()); // "square: 9"
// new Shape("x"); // Cannot create an instance of an abstract class

An abstract class can carry working code and declare holes; an interface can only declare. The cost is that it uses the single inheritance slot and exists at runtime.

Field initialisation

Under strict, a declared field has to be assigned — and the compiler only follows the constructor body:

class A { name: string = "Ana"; }              // 1. initialise

class B {
  name: string;
  constructor() { this.name = "Ana"; }          // 2. assign in the constructor
}

class C { name?: string; }                       // 3. admit it may be absent

class D {
  name!: string;                                 // 4. definite assignment assertion
  constructor() { this.init(); }
  init() { this.name = "Ana"; }                 // invisible to the analysis
}

console.log(new A().name, new B().name, new D().name);

The fourth is an assertion, with the same caveat as every other: nothing checks it. It is the right answer when a framework assigns the field, and a hidden undefined when it is used to silence a real gap.

Order of initialisation

A detail that produces a real class of bug: the base constructor runs before the subclass’s field initialisers.

class Parent {
  constructor() {
    this.setup();   // calls the override, on a half-built object
  }
  setup() { return "parent"; }
}

class Child extends Parent {
  value = "ready";  // assigned after super() returns

  setup() {
    console.log("child setup sees:", this.value); // undefined
  }
}

new Child(); // child setup sees: undefined

Calling an overridable method from a constructor is the mistake. Initialise, then let the caller invoke it.

Common mistakes

Treating private as a security boundary

Mistake. Keeping a token in a private field and assuming it is hidden. Why it fails. It is a compile-time check. The property is readable, enumerable and in JSON.stringify. What to do instead. #token, which the runtime enforces and which JSON skips.

! on a field that is genuinely sometimes missing

Mistake. name!: string because the error was annoying. Why it fails. The assertion removes the check without changing the fact, so the undefined turns up later as a property access on nothing. What to do instead. name?: string and handle it, or initialise it. Keep ! for fields a framework assigns.

Calling an overridable method from the constructor

Mistake. constructor() { this.init(); } where a subclass overrides init. Why it fails. Subclass fields are not initialised yet, so the override reads undefined. What to do instead. Keep constructors to assignment, and expose an init() the caller runs.

Check yourself

4 questions from the bank on what you just read. Answering here does not affect your quiz history.

What is the difference between private and #private on a class field?

A modifier on a constructor parameter does two jobs at once.

What does constructor(private key: string) do?

Code sample
class Entry {
  constructor(private key: string) {}

  describe() {
    return this.key;
  }
}

What can a protected member do that a private one cannot?

What does static mean on a class member in TypeScript?

Practise Access modifiers →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.