Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript class properties initialization order

Tags:

typescript

Say I have a class such as:

class MyClass {
   private readonly prop1 = "prop1"
   private readonly prop2: string

   constructor(
     prop2 = "defaultProp2",
     private readonly prop3 = "defaultProp3"
   ) {
     this.prop2 = prop2
   }

   ...
}

What's the variables initialization order?

like image 380
LppEdd Avatar asked Dec 10 '18 13:12

LppEdd


1 Answers

If you compile to ES5 you can see the order things are initialized in when the code is down compiled (and the order is consistent when native classes are used).

var MyClass = /** @class */ (function () {
    function MyClass(prop2, prop3) {
        if (prop2 === void 0) { prop2 = "defaultProp2"; }
        if (prop3 === void 0) { prop3 = "defaultProp3"; }
        this.prop3 = prop3;
        this.prop1 = "prop1";
        this.prop2 = prop2;
    }
    return MyClass;
}());

So the order is:

  1. Constructor field shorthand
  2. Property initializers
  3. Constructor body.
like image 58
Titian Cernicova-Dragomir Avatar answered Oct 26 '22 06:10

Titian Cernicova-Dragomir