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

A JavaScript specialist with many years of industry experience whose heart beats for Angular. A follower of the "Keep it simple, stupid" principle and a fan of clean code and good architecture. Fearless in the face of the toughest challenges, I always look for simple and effective solutions. As a pragmatist and an enthusiast of new technologies, I passionately follow the trends in the JavaScript world. After hours — a sailor who loves discovering new places and spending time on trips. My favorite motto? "Talk is cheap. Show me the code."

Leave a comment