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';
}
}
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With