Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript Difference in Class Property Initial Value

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';
  }
}
like image 669
Siraj Kakeh Avatar asked Oct 15 '25 16:10

Siraj Kakeh


2 Answers

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.

like image 160
Gil Fink Avatar answered Oct 17 '25 06:10

Gil Fink


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
}
like image 21
shohrukh Avatar answered Oct 17 '25 04:10

shohrukh