loading...

Typescript Constructor Shorthand

satansdeer profile image Maksim Ivanov Originally published at maksimivanov.com on ・1 min read

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

You can write same class using shorter syntax:

class User {
  constructor(
    private name: string,
    private surname: string,
    private age: number
  ) {}
}

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

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.

Discussion

pic
Editor guide
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 Author

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.