Why are underscores added to fields of a typescript class in angular4?

The getter/setter cannot have the name that matches the property name – the following won’t work:

class A {
   get world() {
      return this.world;
   }
}

So the general pattern is to name the internal properties just like a setter/getter only with the edition of an underscore:

class A {
   get world() {
      return this._world;
   }
}

Since JS and therefore TS lacks runtime encapsulation, an underscore usually signifies internal/private/encapsulated property/variable.

But nothing forces you to use underscores. If you name your getter/setter differently, you can avoid adding underscores:

class A {
   get getWorld() {
      return this.world;
   }
}   

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)