Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Constructor assignment of field variables in TypeScript

June 15, 2021 ·

When you work with classes with constructors in TypeScript, the usual way to declare the field variables is like following.

class Book {
    private name: string;
    private author: string;

        name: string, 
        author: string
    ) { = name; = author;

As you can tell, using this approach you will have to declare class field variables at three different places.

  • In the property declaration.
  • In the constructor parameters.
  • In the property assignment in the constructor body.

This is pretty cumbersome if you ask me. What if I tell you there’s a better way to do this?

Enter Constructor Assignment.

Constructor Assignment

Using constructor assignment, you declare the field variables inline as the constructor parameters. We can rewrite the previous example using constructor assignment like so.

class Book {
        private name: string, 
        private author: string
    ) {}

As you can tell, using this approach, you don’t have to write a lot of boilerplate code and things look tidy and concise!

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!