Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Constructor assignment of field variables in TypeScript

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;

    constructor(
        name: string, 
        author: string
    ) {
        this.name = name;
        this.author = 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 {
    constructor(
        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!

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?