Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
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;

        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!

Like this article? Consider leaving a


👋 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.