DEV Community

Maksim Ivanov
Maksim Ivanov

Posted on • Originally published at maksimivanov.com on

Typescript Constructor Shorthand

Here is a thing, in Typescript there is a shorthand to create and assign class properties from constructor params.

Imagine you have following code, let’s say you have class User:

class User {
  private name: string;
  private surname: string;
  private age: number;

  constructor(name: string, surname: string, age: number) {
    this.name = name;
    this.surname = surname;
    this.age = age;
  }
}
Enter fullscreen mode Exit fullscreen mode

You can write same class using shorter syntax:

class User {
  constructor(
    private name: string,
    private surname: string,
    private age: number
  ) {}
}
Enter fullscreen mode Exit fullscreen mode

In this case Typescript will automatically generate thore properties. And yes both definitions will produce same Javascript code:

var User = /** @class */ (function() {
  function User(name, surname, age) {
    this.name = name;
    this.surname = surname;
    this.age = age;
  }
  return User;
})();
Enter fullscreen mode Exit fullscreen mode

And it works not only for private access level modifier, you can use public or protected as well.

So you can use this constructor assignment technique to save some lines of code.

Top comments (6)

Collapse
 
chipit24 profile image
Robert Komaromi

This article was one of the top hits when I was searching for this concept, but I couldn't figure out the official term for this shorthand; turns out it's called "parameter properties", and the official documentation for them is at typescriptlang.org/docs/handbook/2....

Collapse
 
jtlapp profile image
Joe Lapp

Exactly what brought me here: trying to figure out the name of this feature. Kudos for using language I thought to search for.

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

Daaaaang. You know, I generally tend to stay away from classes because I prefer to separate data from logic (you know, “functional programming” style), but sometimes it’s really convenient to use a class for encapsulating a set of shared functions (like a date class). So this is really helpful. Thank you! :)

Collapse
 
satansdeer profile image
Maksim Ivanov

Glad to be helpful :)

Collapse
 
biijoy508 profile image
monir ahmed

Hi, i wonder if you can add exempel shorthand for interface with readonly property. I am having problem.
interface abcd {
readonly x: number;
y: string;
}
class xyz extends abcd {
constructor (readonly x,
y:string=''){}
}
**** when i declare new xyz() says expect 2 parameters, shorthand does not work in this case.

Collapse
 
qhungg289 profile image
Hung Duong Quang

Thanks for a concise explanation!