In TypeScript, all members in a class are public by default. We have to add the private keyword explicitly to control the visibility of the members:
class SimpleCalculator {
private x: number;
private y: number;
z: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
addition() {
z = x + y;
}
subtraction() {
z = x - y;
}
}
class ComplexCalculator {
z: number;
constructor(private x: number, private y: number) { }
multiplication() {
z = this.x * this.y;
}
division() {
z = this.x / this.y;
}
}
Note that in the SimpleCalculator class, we defined x and y as private properties, which will not be visible outside the class. In ComplexCalculator, we defined x and y using parameter properties. These parameter properties will enable us to create and initialize the member in one statement. Here, x and y are created and initialized in the constructor itself without writing any further statements inside it. Also, x and y are private in order to hide them from exposure to consuming classes or modules.