Welcome back! I am Mihir, and in this lesson we will learn public, private, and protected in TypeScript.
These are access modifiers. They control where class members can be used.
public
public members can be accessed from anywhere.
class User {
public name: string;
constructor(name: string) {
this.name = name;
}
}
const user = new User("Mihir");
console.log(user.name);Class members are public by default, so this is the same:
class User {
name: string;
constructor(name: string) {
this.name = name;
}
}private
private members can only be accessed inside the same class.
class BankAccount {
private balance: number = 0;
deposit(amount: number) {
this.balance += amount;
}
getBalance() {
return this.balance;
}
}Valid:
const account = new BankAccount();
account.deposit(500);
console.log(account.getBalance());Invalid:
console.log(account.balance);protected
protected members can be accessed inside the class and its subclasses.
class Person {
protected name: string;
constructor(name: string) {
this.name = name;
}
}
class Employee extends Person {
introduce() {
return `Hi, I am ${this.name}`;
}
}Employee can use this.name because it extends Person.
protected Is Not Public
const employee = new Employee("Mihir");Invalid:
console.log(employee.name);protected does not mean public. It only allows access inside subclasses.
Access Modifiers with Constructor Parameters
class User {
constructor(
public name: string,
private password: string
) {}
checkPassword(value: string) {
return this.password === value;
}
}name becomes public.
password becomes private.
Quick Recap
publicmeans accessible anywhere.- Class members are public by default.
privatemeans accessible only inside the same class.protectedmeans accessible inside the class and subclasses.- Access modifiers help protect class internals.
Next up, we will learn Readonly Class Properties →.