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

  • First, we take a quick look at the features of class definitions in plain JavaScript.
  • Then we explore what additions TypeScript brings to the table.

Table of contents:


Cheat sheet: classes in plain JavaScript

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

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);

Modifier: static

class MyClass2 {

  static staticPublicField = 1;

  static staticPublicMethod() {
    return 2;
  }
}

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

Modifier: # (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();

#typescript

Class definitions in TypeScript
1.40 GEEK