TypeScript Access Modifiers

Control visibility of class members

🔒 What are Access Modifiers?

Access modifiers control the visibility of class properties and methods. TypeScript provides three modifiers: public (accessible everywhere), private (accessible only within class), and protected (accessible within class and subclasses).


class Person {
    public name: string;
    private age: number;
    protected email: string;
}
                                    

Types of Access Modifiers

🌐

Public

Accessible from anywhere (default)

class Car {
    public brand: string;
    
    constructor(brand: string) {
        this.brand = brand;
    }
}
🔒

Private

Accessible only within the class

class BankAccount {
    private balance: number = 0;
    
    deposit(amount: number) {
        this.balance += amount;
    }
}
🛡️

Protected

Accessible in class and subclasses

class Animal {
    protected name: string;
    
    constructor(name: string) {
        this.name = name;
    }
}

🔹 Public Access Modifier

Public members are accessible from anywhere. This is the default modifier:

class Student {
    public name: string;
    public grade: number;
    
    constructor(name: string, grade: number) {
        this.name = name;
        this.grade = grade;
    }
    
    public displayInfo(): void {
        console.log(`${this.name} - Grade: ${this.grade}`);
    }
}

const student = new Student("Alice", 95);
console.log(student.name);      // ✅ Accessible
student.displayInfo();           // ✅ Accessible

Output:

Alice
Alice - Grade: 95

🔹 Private Access Modifier

Private members can only be accessed within the class itself:

class BankAccount {
    private accountNumber: string;
    private balance: number;
    
    constructor(accountNumber: string) {
        this.accountNumber = accountNumber;
        this.balance = 0;
    }
    
    public deposit(amount: number): void {
        this.balance += amount;  // ✅ Accessible within class
    }
    
    public getBalance(): number {
        return this.balance;     // ✅ Accessible within class
    }
}

const account = new BankAccount("12345");
account.deposit(100);
console.log(account.getBalance());  // ✅ Works: 100
// console.log(account.balance);    // ❌ Error: Private property

Output:

100

🔹 Protected Access Modifier

Protected members are accessible within the class and its subclasses:

class Animal {
    protected name: string;
    
    constructor(name: string) {
        this.name = name;
    }
    
    protected makeSound(): void {
        console.log("Some sound");
    }
}

class Dog extends Animal {
    constructor(name: string) {
        super(name);
    }
    
    public bark(): void {
        console.log(`${this.name} says Woof!`);  // ✅ Accessible in subclass
        this.makeSound();                         // ✅ Accessible in subclass
    }
}

const dog = new Dog("Buddy");
dog.bark();                    // ✅ Works
// console.log(dog.name);      // ❌ Error: Protected property
// dog.makeSound();            // ❌ Error: Protected method

Output:

Buddy says Woof!
Some sound

🔹 Comparison Example

See all three modifiers in action:

class Employee {
    public name: string;           // Accessible everywhere
    private salary: number;        // Only within Employee class
    protected department: string;  // Within Employee and subclasses
    
    constructor(name: string, salary: number, dept: string) {
        this.name = name;
        this.salary = salary;
        this.department = dept;
    }
    
    public getDetails(): string {
        return `${this.name} earns $${this.salary}`;
    }
}

class Manager extends Employee {
    public showDepartment(): void {
        console.log(this.department);  // ✅ Protected accessible
        // console.log(this.salary);   // ❌ Private not accessible
    }
}

const emp = new Employee("John", 50000, "IT");
console.log(emp.name);           // ✅ Public accessible
// console.log(emp.salary);      // ❌ Private not accessible
// console.log(emp.department);  // ❌ Protected not accessible

💡 Key Points:

  • Public: Default modifier, accessible everywhere
  • Private: Most restrictive, only within the class
  • Protected: Middle ground, accessible in class and subclasses
  • Use private for sensitive data like passwords or account numbers
  • Use protected when subclasses need access but external code doesn't

🧠 Test Your Knowledge

Which access modifier allows access only within the class?