Turning constructor params into class props in TypeScript

Published on in JavaScript and TypeScript

"Parameter properties" reduce boilerplate in classes, but they can also make the code hard to read.

Table of contents

Definition of parameter properties

Parameter Properties are defined in the TypeScript docs like so:

TypeScript offers special syntax for turning a constructor parameter into a class property with the same name and value. These are called parameter properties and are created by prefixing a constructor argument with one of the visibility modifiers public, private, protected, or readonly.

Example

The two classes below are effectively identical.

Before: ordinary class properties

// Ordinary class properties
class Foo {
  public readonly x: number
  protected y: number
  private z: number

  constructor(x: number, y: number, z: number) {
    this.x = x
    this.y = y
    this.z = z
  }
}

After: parameter properties

// Parameter properties
class Foo {
  constructor(
    public readonly x: number,
    protected y: number,
    private z: number
  ) {}
}

Verdict

I like that parameter properties reduce boilerplate and verbosity. But they are potentially confusing if they are mixed with ordinary class properties – it might be hard to see at a glance all the properties that the class has.