The private modifier in TypeScript
The private modifier is used in cases where it is necessary to close access to properties and methods outside the class. In this case, even in descendant classes it will not be possible to access these properties.
Let's look at an example. Let's create a private property User in the class name:
class User {
private name: string;
constructor(name: string) {
this.name = name;
}
}
Let's create an object of the class by passing the value of our property to the constructor:
let user: User = new User('john');
Now trying to read this private property outside the class will result in an error:
console.log(user.name); //
An attempt to write something to this property from outside the class will also result in an error:
user.name = 'eric'; //
But inside the class methods it will be possible to both read and change the value of our private property:
class User {
private name: string;
constructor(name: string) {
this.name = name;
}
public getName() {
return this.name; // let's read the property
}
public setName(name: string) {
this.name = name; // let's write a new value for the property
}
}
Make a class User containing private properties with name and age. Let their initial values be set via the constructor.
In your User class, make public methods getName and getAge that allow you to get the values of the corresponding private properties.
In your User class, make public methods setName and setAge that allow you to change the values of the corresponding private properties.