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.

Leave a comment