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.

1
class ExampleClass2 {
2
name: string;
3
4
constructor() {
5
this.name = "John";
6
}
7
}

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.

1
class ExampleClass1 {
2
name = "John";
3
}

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

1
class ExampleClass1 {
2
constructor() {
3
this.name = "John";
4
}
5
}
6
class ExampleClass2 {
7
constructor() {
8
this.name = "John";
9
}
10
}

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.

Leave a comment