Tackling TypeScript
Please support this book: buy it or donate
(Ad, please don’t block.)

16 Class definitions in TypeScript



In this chapter, we examine how class definitions work in TypeScript:

16.1 Cheat sheet: classes in plain JavaScript

This section is a cheat sheet for class definitions in plain JavaScript.

16.1.1 Basic members of classes

class OtherClass {}

class MyClass1 extends OtherClass {

  publicInstanceField = 1;

  constructor() {
    super();
  }

  publicPrototypeMethod() {
    return 2;
  }
}

const inst1 = new MyClass1();
assert.equal(inst1.publicInstanceField, 1);
assert.equal(inst1.publicPrototypeMethod(), 2);

  The next sections are about modifiers

At the end, there is a table that shows how modifiers can be combined.

16.1.2 Modifier: static

class MyClass2 {

  static staticPublicField = 1;

  static staticPublicMethod() {
    return 2;
  }
}

assert.equal(MyClass2.staticPublicField, 1);
assert.equal(MyClass2.staticPublicMethod(), 2);

16.1.3 Modifier-like name prefix: # (private)

class MyClass3 {
  #privateField = 1;

  #privateMethod() {
    return 2;
  }

  static accessPrivateMembers() {
    // Private members can only be accessed from inside class definitions
    const inst3 = new MyClass3();
    assert.equal(inst3.#privateField, 1);
    assert.equal(inst3.#privateMethod(), 2);
  }
}
MyClass3.accessPrivateMembers();

Warning for JavaScript:

TypeScript has been supporting private fields since version 3.8 but does not currently support private methods.

16.1.4 Modifiers for accessors: get (getter) and set (setter)

Roughly, accessors are methods that are invoked by accessing properties. There are two kinds of accessors: getters and setters.

class MyClass5 {
  #name = 'Rumpelstiltskin';
  
  /** Prototype getter */
  get name() {
    return this.#name;
  }

  /** Prototype setter */
  set name(value) {
    this.#name = value;
  }
}
const inst5 = new MyClass5();
assert.equal(inst5.name, 'Rumpelstiltskin'); // getter
inst5.name = 'Queen'; // setter
assert.equal(inst5.name, 'Queen'); // getter

16.1.5 Modifier for methods: * (generator)

class MyClass6 {
  * publicPrototypeGeneratorMethod() {
    yield 'hello';
    yield 'world';
  }
}

const inst6 = new MyClass6();
assert.deepEqual(
  [...inst6.publicPrototypeGeneratorMethod()],
  ['hello', 'world']);

16.1.6 Modifier for methods: async

class MyClass7 {
  async publicPrototypeAsyncMethod() {
    const result = await Promise.resolve('abc');
    return result + result;
  }
}

const inst7 = new MyClass7();
inst7.publicPrototypeAsyncMethod()
  .then(result => assert.equal(result, 'abcabc'));

16.1.7 Computed class member names

const publicInstanceFieldKey = Symbol('publicInstanceFieldKey');
const publicPrototypeMethodKey = Symbol('publicPrototypeMethodKey');

class MyClass8 {

  [publicInstanceFieldKey] = 1;

  [publicPrototypeMethodKey]() {
    return 2;
  }
}

const inst8 = new MyClass8();
assert.equal(inst8[publicInstanceFieldKey], 1);
assert.equal(inst8[publicPrototypeMethodKey](), 2);

Comments:

16.1.8 Combinations of modifiers

Fields (no level means that a construct exists at the instance level):

Level Visibility
(instance)
(instance) #
static
static #

Methods (no level means that a construct exists at the prototype level):

Level Accessor Async Generator Visibility
(prototype)
(prototype) get
(prototype) set
(prototype) async
(prototype) *
(prototype) async *
(prototype-associated) #
(prototype-associated) get #
(prototype-associated) set #
(prototype-associated) async #
(prototype-associated) * #
(prototype-associated) async * #
static
static get
static set
static async
static *
static async *
static #
static get #
static set #
static async #
static * #
static async * #

Limitations of methods:

16.1.9 Under the hood

It’s important to keep in mind that with classes, there are two chains of prototype objects:

Consider the following plain JavaScript example:

class ClassA {
  static staticMthdA() {}
  constructor(instPropA) {
    this.instPropA = instPropA;
  }
  prototypeMthdA() {}
}
class ClassB extends ClassA {
  static staticMthdB() {}
  constructor(instPropA, instPropB) {
    super(instPropA);
    this.instPropB = instPropB;
  }
  prototypeMthdB() {}
}
const instB = new ClassB(0, 1);

Fig. 1 shows what the prototype chains look like that are created by ClassA and ClassB.

Figure 1: The classes ClassA and ClassB create two prototype chains: One for classes (left-hand side) and one for instances (right-hand side).

16.1.10 More information on class definitions in plain JavaScript

16.2 Non-public data slots in TypeScript

By default, all data slots in TypeScript are public properties. There are two ways of keeping data private:

We’ll look at both next.

Note that TypeScript does not currently support private methods.

16.2.1 Private properties

Private properties are a TypeScript-only (static) feature. Any property can be made private by prefixing it with the keyword private (line A):

class PersonPrivateProperty {
  private name: string; // (A)
  constructor(name: string) {
    this.name = name;
  }
  sayHello() {
    return `Hello ${this.name}!`;
  }
}

We now get compile-time errors if we access that property in the wrong scope (line A):

const john = new PersonPrivateProperty('John');

assert.equal(
  john.sayHello(), 'Hello John!');

// @ts-expect-error: Property 'name' is private and only accessible
// within class 'PersonPrivateProperty'. (2341)
john.name; // (A)

However, private doesn’t change anything at runtime. There, property .name is indistinguishable from a public property:

assert.deepEqual(
  Object.keys(john),
  ['name']);

We can also see that private properties aren’t protected at runtime when we look at the JavaScript code that the class is compiled to:

class PersonPrivateProperty {
  constructor(name) {
    this.name = name;
  }
  sayHello() {
    return `Hello ${this.name}!`;
  }
}

16.2.2 Private fields

Private fields are a new JavaScript feature that TypeScript has supported since version 3.8:

class PersonPrivateField {
  #name: string;
  constructor(name: string) {
    this.#name = name;
  }
  sayHello() {
    return `Hello ${this.#name}!`;
  }
}

This version of Person is mostly used the same way as the private property version:

const john = new PersonPrivateField('John');

assert.equal(
  john.sayHello(), 'Hello John!');

However, this time, the data is completely encapsulated. Using the private field syntax outside classes is even a JavaScript syntax error. That’s why we have to use eval() in line A so that we can execute this code:

assert.throws(
  () => eval('john.#name'), // (A)
  {
    name: 'SyntaxError',
    message: "Private field '#name' must be declared in "
      + "an enclosing class",
  });

assert.deepEqual(
  Object.keys(john),
  []);

The compilation result is much more complicated now (slightly simplified):

var __classPrivateFieldSet = function (receiver, privateMap, value) {
  if (!privateMap.has(receiver)) {
    throw new TypeError(
      'attempted to set private field on non-instance');
  }
  privateMap.set(receiver, value);
  return value;
};

// Omitted: __classPrivateFieldGet

var _name = new WeakMap();
class Person {
  constructor(name) {
    // Add an entry for this instance to _name
    _name.set(this, void 0);

    // Now we can use the helper function:
    __classPrivateFieldSet(this, _name, name);
  }
  // ···
}

This code uses a common technique for keeping instance data private:

More information on this topic: see “JavaScript for impatient programmers”.

16.2.3 Private properties vs. private fields

16.2.4 Protected properties

Private fields and private properties can’t be accessed in subclasses (line A):

class PrivatePerson {
  private name: string;
  constructor(name: string) {
    this.name = name;
  }
  sayHello() {
    return `Hello ${this.name}!`;
  }
}
class PrivateEmployee extends PrivatePerson {
  private company: string;
  constructor(name: string, company: string) {
    super(name);
    this.company = company;
  }
  sayHello() {
    // @ts-expect-error: Property 'name' is private and only
    // accessible within class 'PrivatePerson'. (2341)
    return `Hello ${this.name} from ${this.company}!`; // (A)
  }  
}

We can fix the previous example by switching from private to protected in line A (we also switch in line B, for consistency’s sake):

class ProtectedPerson {
  protected name: string; // (A)
  constructor(name: string) {
    this.name = name;
  }
  sayHello() {
    return `Hello ${this.name}!`;
  }
}
class ProtectedEmployee extends ProtectedPerson {
  protected company: string; // (B)
  constructor(name: string, company: string) {
    super(name);
    this.company = company;
  }
  sayHello() {
    return `Hello ${this.name} from ${this.company}!`; // OK
  }  
}

16.3 Private constructors

Constructors can be private, too. That is useful when we have static factory methods and want clients to always use those methods, never the constructor directly. Static methods can access private class members, which is why the factory methods can still use the constructor.

In the following code, there is one static factory method DataContainer.create(). It sets up instances via asynchronously loaded data. Keeping the asynchronous code in the factory method enables the actual class to be completely synchronous:

class DataContainer {
  #data: string;
  static async create() {
    const data = await Promise.resolve('downloaded'); // (A)
    return new this(data);
  }
  private constructor(data: string) {
    this.#data = data;
  }
  getData() {
    return 'DATA: '+this.#data;
  }
}
DataContainer.create()
  .then(dc => assert.equal(
    dc.getData(), 'DATA: downloaded'));

In real-world code, we would use fetch() or a similar Promise-based API to load data asynchronously in line A.

The private constructor prevents DataContainer from being subclassed. If we want to allow subclasses, we have to make it protected.

16.4 Initializing instance properties

16.4.1 Strict property initialization

If the compiler setting --strictPropertyInitialization is switched on (which is the case if we use --strict), then TypeScript checks if all declared instance properties are correctly initialized:

However, sometimes we initialize properties in a manner that TypeScript doesn’t recognize. Then we can use exclamation marks (definite assignment assertions) to switch off TypeScript’s warnings (line A and line B):

class Point {
  x!: number; // (A)
  y!: number; // (B)
  constructor() {
    this.initProperties();
  }
  initProperties() {
    this.x = 0;
    this.y = 0;
  }
}
16.4.1.1 Example: setting up instance properties via objects

In the following example, we also need definite assignment assertions. Here, we set up instance properties via the constructor parameter props:

class CompilerError implements CompilerErrorProps { // (A)
  line!: number;
  description!: string;
  constructor(props: CompilerErrorProps) {
    Object.assign(this, props); // (B)
  }
}

// Helper interface for the parameter properties
interface CompilerErrorProps {
  line: number,
  description: string,
}

// Using the class:
const err = new CompilerError({
  line: 123,
  description: 'Unexpected token',
});

Notes:

16.4.2 Making constructor parameters public, private, or protected

If we use the keyword public for a constructor parameter, then TypeScript does two things for us:

Therefore, the following two classes are equivalent:

class Point1 {
  constructor(public x: number, public y: number) {
  }
}

class Point2 {
  x: number;
  y: number;
  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }
}

If we use private or protected instead of public, then the corresponding instance properties are private or protected (not public).

16.5 Abstract classes

Two constructs can be abstract in TypeScript:

The following code demonstrates abstract classes and methods.

On one hand, there is the abstract superclass Printable and its helper class StringBuilder:

class StringBuilder {
  string = '';
  add(str: string) {
    this.string += str;
  }
}
abstract class Printable {
  toString() {
    const out = new StringBuilder();
    this.print(out);
    return out.string;
  }
  abstract print(out: StringBuilder): void;
}

On the other hand, there are the concrete subclasses Entries and Entry:

class Entries extends Printable {
  entries: Entry[];
  constructor(entries: Entry[]) {
    super();
    this.entries = entries;
  }
  print(out: StringBuilder): void {
    for (const entry of this.entries) {
      entry.print(out);
    }
  }
}
class Entry extends Printable {
  key: string;
  value: string;
  constructor(key: string, value: string) {
    super();
    this.key = key;
    this.value = value;
  }
  print(out: StringBuilder): void {
    out.add(this.key);
    out.add(': ');
    out.add(this.value);
    out.add('\n');
  }
}

And finally, this is us using Entries and Entry:

const entries = new Entries([
  new Entry('accept-ranges', 'bytes'),
  new Entry('content-length', '6518'),
]);
assert.equal(
  entries.toString(),
  'accept-ranges: bytes\ncontent-length: 6518\n');

Notes about abstract classes: