Access modifiers

Similar to .NET, TypeScript allows you to define access modifiers to class members. This is a great feature as it expands your ability to author well-designed, encapsulated, and safer code. In JavaScript, for example, a common convention to represent private and internal code is to use an underscore (_) prefix, which should no longer be needed.

TypeScript classes support multiple access modifiers – private, protected, and public (default):

  • Private: Members are accessible from within the instance of the same class
  • Public: Members are accessible everywhere
  • Protected: Members are accessible from within the instance of the same or a derived class

Consider the following example:

class SumCalculator {
protected history: Calculable[] = [];

constructor(private saveHistory: boolean) { }

sum(left: number, right: number): number {
return this.calcCore(left, right);
}

private calcCore(left: number, right: number): number {
if (this.saveHistory) this.history.push({left, right});
return left + right;
}
}

const calc = new SumCalculator();
console.log(calc.sum(2,3));

If you look closely, the preceding example defines an access modifier for the constructor argument saveHistory. TypeScript supports this special construct to ease a very common need. More often than not, constructor arguments are simply being set to instance fields, and that is exactly the effect in place.
If you add an access modifier or read-only to a constructor argument, TypeScript sets an instance field with the same name to the value of the argument automatically for you.

For example, both of the following statements are equivalent:

class SumCalculator {
private saveHistory: boolean;
constructor(saveHistory: boolean) {
this.saveHistory = saveHistory;
}
}

class SumCalculator {
constructor(private saveHistory: boolean) {}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.72.74