Typescript Public Private And Protected Modifiers Complete Guide

 Last Update:2025-06-22T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    7 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of TypeScript Public, Private, and Protected Modifiers

1. Public Modifier

  • Definition: The public modifier allows class members to be accessible from anywhere, both within the class and outside it. If no access modifier is specified, public is the default.

  • Syntax Example:

    class Employee {
      public firstName: string;
      public lastName: string;
    
      public constructor(firstName: string, lastName: string) {
        this.firstName = firstName;
        this.lastName = lastName;
      }
    
      public displayInfo(): void {
        console.log(`Employee: ${this.firstName} ${this.lastName}`);
      }
    }
    
    // Accessing public members outside the class
    let john = new Employee('John', 'Doe');
    john.displayInfo(); // Output: Employee: John Doe
    
  • Important Info:

    • Flexibility: Offers the highest level of accessibility, but be cautious as it can lead to unintended modifications or interactions.
    • No Restrictions: Once a member is declared public, it can be accessed and modified from anywhere outside the class.

2. Private Modifier

  • Definition: The private modifier restricts access to the class members, allowing them to be accessed only within the declaring class itself and not from outside or derived classes.

  • Syntax Example:

    class Employee {
      private firstName: string;
      private lastName: string;
    
      public constructor(firstName: string, lastName: string) {
        this.firstName = firstName;
        this.lastName = lastName;
      }
    
      private displayInfo(): void {
        console.log(`Employee: ${this.firstName} ${this.lastName}`);
      }
    
      public showDetails(): void {
        this.displayInfo();
      }
    }
    
    let john = new Employee('John', 'Doe');
    john.showDetails(); // Output: Employee: John Doe
    // john.displayInfo(); // Error: Property 'displayInfo' is private and only accessible within class 'Employee'.
    
  • Important Info:

    • Encapsulation: Critical for protecting class state from external manipulation, enhancing security and maintainability.
    • Compiler Enforced: TypeScript's compile-time validation ensures that private members are not accessible outside their class.

3. Protected Modifier

  • Definition: The protected modifier allows class members to be accessed within the class it is declared and any derived classes, but not from outside the class hierarchy.

  • Syntax Example:

    class Employee {
      protected firstName: string;
      protected lastName: string;
    
      public constructor(firstName: string, lastName: string) {
        this.firstName = firstName;
        this.lastName = lastName;
      }
    
      protected displayInfo(): void {
        console.log(`Employee: ${this.firstName} ${this.lastName}`);
      }
    }
    
    class Manager extends Employee {
      private department: string;
    
      public constructor(firstName: string, lastName: string, department: string) {
        super(firstName, lastName);
        this.department = department;
      }
    
      public showDetails(): void {
        this.displayInfo(); // Accessible within derived class
        console.log(`Department: ${this.department}`);
      }
    }
    
    let jane = new Manager('Jane', 'Smith', 'HR');
    jane.showDetails(); // Output: Employee: Jane Smith \n Department: HR
    // jane.displayInfo(); // Error: Property 'displayInfo' is protected and only accessible within class 'Employee' and its subclasses.
    
  • Important Info:

    • Inheritance: Useful when designing a class hierarchy where access to certain members should be limited but still available to derived classes for customization or extension.
    • Extendibility: Facilitates the creation of flexible and modular codebases by allowing controlled access to members within the class hierarchy.

Summary

  • Public: Highest accessibility, default if no modifier is specified.
  • Private: Restricted to the declaring class, offering strong data encapsulation.
  • Protected: Accessible within the class and its derived classes, supporting class inheritance and extensibility.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement TypeScript Public, Private, and Protected Modifiers

Let's go through complete examples for each of these modifiers step by step.

1. public Modifier

The public modifier is the default. When you don't specify a modifier, members are public by default, meaning they can be accessed from anywhere.

Example:

class Animal {
  public name: string;

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

  public makeSound(): void {
    console.log("Some generic animal sound");
  }
}

// Creating an instance of Animal
const myAnimal = new Animal("Generic Animal");

// Accessing public properties and methods
console.log(myAnimal.name); // Output: Generic Animal
myAnimal.makeSound(); // Output: Some generic animal sound

2. private Modifier

The private modifier restricts access to the private members from outside the class. They can only be accessed within the class itself.

Example:

class Animal {
  private name: string;

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

  private makeSound(): void {
    console.log("Some generic animal sound");
  }

  public getName(): string {
    return this.name;
  }

  public getSound(): void {
    this.makeSound();
  }
}

// Creating an instance of Animal
const myAnimal = new Animal("Generic Animal");

// Trying to access private properties and methods will result in errors
// console.log(myAnimal.name); // Error: Property 'name' is private and only accessible within class 'Animal'.
// myAnimal.makeSound(); // Error: Property 'makeSound' is private and only accessible within class 'Animal'.

// Accessing via public methods
console.log(myAnimal.getName()); // Output: Generic Animal
myAnimal.getSound(); // Output: Some generic animal sound

3. protected Modifier

The protected modifier allows class members to be accessed within their own class and any subclasses (derived classes). They cannot be accessed from outside the class or its subclasses.

Example:

class Animal {
  protected name: string;

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

  protected makeSound(): void {
    console.log("Some generic animal sound");
  }
}

// Subclass that extends Animal
class Dog extends Animal {
  constructor(name: string) {
    super(name);
  }

  // Accessing protected members within the subclass
  public bark(): void {
    console.log(`${this.name} says Woof!`); // Accessing protected property 'name'
    this.makeSound(); // Accessing protected method 'makeSound'
  }
}

// Creating an instance of Dog
const myDog = new Dog("Buddy");

// Trying to access protected properties and methods will result in errors
// console.log(myDog.name); // Error: Property 'name' is protected and only accessible within class 'Animal' and its subclasses.
// myDog.makeSound(); // Error: Property 'makeSound' is protected and only accessible within class 'Animal' and its subclasses.

// Accessing via public method
myDog.bark(); // Output: Buddy says Woof!
// Output: Some generic animal sound

Summary

  • public: Accessible from anywhere.
  • private: Accessible only within the class itself.
  • protected: Accessible within the class itself and any subclasses.

Understanding these access modifiers will help you manage the visibility and encapsulation of your class members effectively.

Top 10 Interview Questions & Answers on TypeScript Public, Private, and Protected Modifiers

1. What are the differences between public, private, and protected access modifiers in TypeScript?

  • Public: Members (properties and methods) are accessible from anywhere. By default, members are public.
  • Private: Members are only accessible within the class itself and cannot be accessed from outside the class.
  • Protected: Members are accessible within the class and by derived classes but not from external code.

2. How do you declare a member as private in TypeScript?

You declare a member as private by using the private keyword. For example:

class User {
    private name: string;

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

In the above example, name is a private property and cannot be accessed outside of the User class.

3. Can you provide an example of using the protected access modifier in TypeScript?

Sure, here is an example using the protected modifier:

class Vehicle {
    protected brand: string;

    constructor(brand: string) {
        this.brand = brand;
    }
}

class Car extends Vehicle {
    public displayBrand(): void {
        console.log(this.brand); // Accessible here because Car extends Vehicle
    }
}

const myCar = new Car("Toyota");
myCar.displayBrand(); // Outputs "Toyota"
console.log(myCar.brand); // Error, property 'brand' is protected and not accessible here

4. What happens if you try to access a private or protected member from outside the class or derived class?

TypeScript enforces access restrictions at compile time. Attempting to access a private or protected member from outside the class or derived class will result in a compile-time error. For example:

const user = new User("John Doe");
console.log(user.name); // Error: Property 'name' is private and only accessible within class 'User'.

5. Can you use public, private, and protected modifiers with class methods in TypeScript?

Yes, you can use these modifiers with class methods as well. The same rules apply:

  • Public: The method is accessible anywhere.
  • Private: The method is only accessible within the class.
  • Protected: The method is accessible within the class and by derived classes.

Example:

class Calculator {
    private add(x: number, y: number): number {
        return x + y;
    }

    public displayResult(x: number, y: number): void {
        const result = this.add(x, y);
        console.log(`Sum: ${result}`);
    }
}

6. How do you choose between public, private, and protected access modifiers when designing a class?

  • Use public when you want the property or method to be accessible from anywhere.
  • Use private when you want to hide the implementation details of a class and only allow access via public methods (encapsulation).
  • Use protected when you need a property or method to be accessible within the class and subclasses, but not from external code.

7. Can you use TypeScript's access modifiers with static properties and methods?

You can apply access modifiers to static properties and methods in the same way. Example:

class MathUtils {
    static private pi = 3.14;

    static public calculateArea(radius: number): number {
        return MathUtils.pi * Math.pow(radius, 2);
    }
}

console.log(MathUtils.calculateArea(5)); // OK
console.log(MathUtils.pi); // Error: Property 'pi' is private and only accessible within class 'MathUtils'.

8. Does TypeScript enforce access restrictions at runtime?

TypeScript enforces access restrictions at compile time. The resulting JavaScript code does not have built-in access control mechanisms. TypeScript's access modifiers are purely for compile-time protection and do not prevent access at runtime using JavaScript's capability.

9. Can you override private or protected members in a subclass?

Protected members can be overridden in a subclass because they are meant to be accessible within the class hierarchy. However, private members cannot be overridden because they are limited to the class they are declared in. Attempting to override private members results in a compile-time error.

class Parent {
    private privateMethod(): void {
        console.log("Parent's private method");
    }

    protected protectedMethod(): void {
        console.log("Parent's protected method");
    }
}

class Child extends Parent {
    // privateMethod() // Error: Property 'privateMethod' is private and only accessible within class 'Parent'
    
    protected protectedMethod(): void {
        console.log("Child's overridden protected method");
    }
}

10. When should you avoid using access modifiers in TypeScript?

Avoid using access modifiers when you want to expose all internal details of a class or when you are working on small scripts where the impact of encapsulation is negligible. However, as a best practice, use access modifiers to encapsulate your code, limit side effects, and follow the principles of good object-oriented design.

You May Like This Related .NET Topic

Login to post a comment.