Parameter properties in TypeScript

David Ford
1 min readJun 25, 2017

Here is a neat trick that can save a lot of boilerplate code when creating classes. I recently learned this from my colleague Max Caber.

Suppose you have a simple class with two properties. And the constructor is used to initialize the properties like this:

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

A very common pattern in objected oriented programming. In TypeScript there is a shorthand for this pattern:

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

By simply prefixing the constructor arg with the word private (or public or readonly) it automatically creates the property and initializes it from the constructor args.

Kotlin

As an aside, here is how you would do the same thing in Kotlin:

class Point(var x:Int, var y:Int)

Dart

And in Dart:

class Point {
int x, y;
Point(this.x, this.y);
}

--

--