Classes in TypeScript

Intermediate

Introduction

Classes bundle data with the methods that work on it. JavaScript has classes, and TypeScript adds what makes them safe to use in a large program: a type for every field, checks that every field is set, and access modifiers that say which code may touch which members. This lesson covers the class features you will use every day.

How it works

Fields are declared in the class body with their types. In strict mode each one must get a value, either where it is declared or in the constructor:

class Account {
  owner: string;
  balance = 0; // the type number is inferred
  constructor(owner: string) {
    this.owner = owner;
  }
}

Writing a field and then copying a constructor parameter into it is so common that TypeScript has a shortcut. A parameter property puts public, private, protected or readonly in front of a constructor parameter, which declares the field and sets it: constructor(public owner: string) {} does the same as the code above.

Access modifiers control who may use a member:

  • public (the default): any code.
  • private: only code inside this class.
  • protected: this class and classes that extend it.

These are checked by TypeScript and erased afterwards, so at run time the field is an ordinary property. JavaScript's own #private fields, written #count, are private at run time too: no code outside the class can read them at all, and they do not even appear when the object is printed. readonly fields can be set only in their declaration or the constructor.

A getter get value() runs when the property is read, and a setter set value(n) runs when it is assigned. To callers they look like a plain property, but they can compute a result or reject a bad value. A static member belongs to the class itself: Counter.created counts objects across the whole program, and is read through the class name, not through an object.

Example

// A class with a static field, a private field, a parameter property, a getter and a setter.
class Counter {
  static created = 0; // one value shared by the class, not by each object
  #count = 0; // private at run time too
  private readonly step: number;

  constructor(public label: string, step = 1) {
    this.step = step;
    Counter.created++;
  }

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

  get value(): number {
    return this.#count;
  }

  set value(n: number) {
    if (n < 0) throw new Error("A count cannot be negative");
    this.#count = n;
  }
}

const clicks = new Counter("clicks");
const pages = new Counter("pages", 10);
clicks.increment();
clicks.increment();
pages.increment();
pages.value = 5; // runs the setter
console.log(clicks.label, clicks.value, pages.label, pages.value, Counter.created);
Open in compiler

Line by line

  1. created is static: there is one value, read as Counter.created.
  2. #count is private at run time; step is private to TypeScript and cannot change after the constructor.
  3. public label in the constructor's parameters declares and sets the field label.
  4. increment adds the step and returns the new count.
  5. pages.value = 5 runs the setter, which checks the value before storing it.

Expected result

clicks 2 pages 5 2

In the real world

Classes model things with state and rules: a shopping cart, a connection pool, a game character. Frameworks such as Angular and NestJS are built around TypeScript classes with parameter properties for their dependencies. Libraries hide internal state in private or #private fields so that users can rely only on the public methods, which lets the authors change the internals safely.

Common mistakes

  • Declaring a field without setting it: strict mode reports TS2564, "has no initializer and is not definitely assigned in the constructor".
  • Thinking private hides data at run time: only #private fields do.
  • Forgetting this. inside methods, which refers to a different variable or none at all.
  • Using a setter without a getter, which makes the property impossible to read back.

Best practices

  • Make fields private (or #private) by default, and expose only what callers need.
  • Use parameter properties for fields that are just copies of constructor arguments.
  • Validate in setters or methods, so an object can never get into an invalid state.

Summary

TypeScript classes have typed fields that must be initialised, parameter properties to declare and set fields at once, and access modifiers: public, private and protected, checked at compile time, plus JavaScript's #private fields, enforced at run time. Getters and setters compute or validate behind a property, and static members belong to the class itself.

Quick check

1. What does constructor(private name: string) {} do?
2. Which kind of private member is hidden at run time too?
3. How is a static field read?
4. What runs when code assigns to a property that has a setter?

Key takeaways

  • Every field has a type, and strict mode requires each to be set by the constructor or an initialiser.
  • private and protected are checked by TypeScript; #name fields are private at run time too.
  • Getters and setters look like properties to callers but can compute or validate.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.