By default, a property in a class has public visibility.
class Trinket {
name: string;
constructor (name: string) {
this.name = name;
}
}
We can access the ‘name’ property outside of the class:
let jewelry = new Trinket('Pale Lavender Ioun Stone');
console.log(jewelry.name);
// ^ This is legal, because the 'name' property has public visibility
In many cases, leaving a class’s property public is undesirable, because it violates the principles of encapsulation. If this is the case, you can restrict direct access to the property to the class itself:
class Necklace {
private name: string;
constructor (name: string) {
this.name = name;
}
}
Now we can’t access the property outside the class:
jewelry = new Necklace('Pale Lavender Ioun Stone');
console.log(jewelry.name);
// ^ This will cause an error, because the 'name' property has private visibility