Modifiers
| Public by default | |
| private walls | |
| Protected for children | |
| Readonly fields |
Public by default
Members are public unless marked otherwise. Public fields and methods form the normal way to use an object.
class User {
public name: string = "Guest";
}
const user = new User();
console.log(user.name);
private walls
Mark internals as private to hide them from outside code. Only methods of the same class can read or change a private member.
Outside access is a compile error, which keeps refactoring safe.
class Vault {
private code: string = "1234";
unlock(attempt: string): boolean {
return attempt === this.code;
}
}
const vault = new Vault();
console.log(vault.unlock("1234"));
Protected for children
Protected members are hidden from outside code but visible inside child classes. Use protected for helpers that children need and strangers do not.
class Animal {
protected legs: number = 4;
}
class Dog extends Animal {
describe(): string {
return "Legs: " + this.legs;
}
}
Readonly fields
Mark a field as readonly when it is set once and never changed after. The compiler rejects later assignments to that field.
class Config {
readonly host: string = "localhost";
}
const config = new Config();
console.log(config.host);
Next: implements
Article author: Arthur Isaev