Initialize class property in a declaration, not in a constructor

There is no difference in JS when you split property into declaration and initialization so you can choose the shortest version: declare and initialize in the same line.

October 14, 2023 typescript

Split property into declaration and initialization

TypeScript requires to declare class properties. That means you have to always define property and type. To initialize property you can use the constructor.

class ExampleClass2 {
name: string;
constructor() {
this.name = "John";
}
}

Declare and initialize in the same line

When you know the initial value then TypeScript allows you to initialize a property in the same line. That means you do not have to even define the constructor. TypeScript will do it for you.

class ExampleClass1 {
name = "John";
}

JS code after compilation

As you can see there is no difference between the two of them (you can see the preview on TS Playground) so you can choose what but personally I would choose the shortest (declare and initialize in the same line).

class ExampleClass1 {
constructor() {
this.name = "John";
}
}
class ExampleClass2 {
constructor() {
this.name = "John";
}
}

Do you like the content?

Your support helps me continue my work. Please consider making a donation.

Donations are accepted through PayPal or Stripe. You do not need a account to donate. All major credit cards are accepted.

Portrait of the author

About me

On a daily basis, I work as a Front-End Developer with a primary focus on JavaScript. I feel most comfortable with Angular and NestJS, but I’m always eager to venture beyond a single tech stack. I effectively leverage AI tools in my workflow, which allows me to quickly onboard into new technologies and write code in other languages or frameworks whenever needed.

After hours, I bring my passion for tech into the physical world. I run my own homelab, where I experiment with server management and build home automation and monitoring powered by Home Assistant.

Leave a comment