4

In TypeScript, is there any difference between giving the class property its initial value on definition vs in the constructor?

class Car {
  engine = 'hybrid';
}

VS.

class Car {
  engine: string;
  constructor() {
    this.engine = 'hybrid';
  }
}
shohrukh
  • 2,989
  • 3
  • 23
  • 38
Siraj Kakeh
  • 741
  • 6
  • 20

3 Answers3

3

There is no difference between both of those options. When compiling both of the code versions you provided you will get the same result:

var Car = /** @class */ (function () {
    function Car() {
        this.engine = 'hybrid';
    }
    return Car;
}());

You can check it by yourself in TypeScript playground.

Gil Fink
  • 747
  • 9
  • 10
2

For your example, when the code transpiled to JS - there is no difference (see @Gil's answer).

In TypeScript actually there is a difference (but not in your example, since your constructor does not have any arguments). If you want to pass arguments to the constructor class - then the magic of TypeScript happens because TS includes a concise way to create and assign a class instance property from a constructor parameter.

Let's say we have a class:

class MyClass {
  private prop: string;

  constructor(prop: string) {
    this.prop = prop;
  }
}

You can write it in ONE line of code adding property modificators:

class MyClass {
  constructor(private prop: string) { }
}

This will create prop property in the class and also initialize it with new value from constructor argument. Define private/public/protected modificators is up to you (it depends on your class's logic).

Last case - if you don't set modificator:

class MyClass {
  constructor(prop: string) {
    // prop variable is available here
  }
  // prop variable is not available outside the constructor method
}
shohrukh
  • 2,989
  • 3
  • 23
  • 38
0

Prefer constructor. Its purpose is to initialise variables. Somebody looking at your code might first look at the constructor to see initialised values