Open In App

Access Modifiers in TypeScript

Last Updated : 23 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In TypeScript, access modifiers control the visibility and accessibility of class members, such as properties and methods, aligning with the principles of encapsulation and information hiding in object-oriented programming.

  • Public: Members are accessible from anywhere; this is the default modifier if none is specified.
  • Private: Members are accessible only within the class they are defined in.
  • Protected: Members are accessible within the class they are defined in and in subclasses.
class Animal {
    public name: string;
    private age: number;
    protected species: string;

    constructor(name: string, age: number, species: string) {
        this.name = name;
        this.age = age;
        this.species = species;
    }

    public getInfo(): string {
        return `${this.name} is a ${this.species}.`;
    }
}

class Dog extends Animal {
    constructor(name: string, age: number) {
        super(name, age, 'Dog');
    }

    public getDetails(): string {
        return `${this.name} is a ${this.species} and is ${this.age} years old.`;
    }
}

const myDog = new Dog('Buddy', 3);
console.log(myDog.name); // Accessible
console.log(myDog.getInfo()); // Accessible
console.log(myDog.getDetails()); // Accessible
  • name is public: accessible from anywhere.
  • age is private: accessible only within the Animal class.
  • species is protected: accessible within Animal and its subclass Dog.

Output:

Buddy
Buddy is a Dog.
Buddy is a Dog and is 3 years old.

Types of Access Modifiers

1) Public Access Modifier

The public modifier allows class members to be accessible from anywhere. By default, all class members are public if no access modifier is specified.

class Animal {
    public name: string;

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

    public makeSound(): void {
        console.log(`${this.name} makes a sound.`);
    }
}

const dog = new Animal('Dog');
console.log(dog.name); // Accessible
dog.makeSound(); // Accessible
  • name and makeSound are public, allowing access from outside the class.
  • We can create an instance of Animal and access its name property and makeSound method directly.

Output:

Dog
Dog makes a sound.

2. Private Access Modifier

The private modifier restricts access to class members, making them accessible only within the class they are defined. This ensures encapsulation and protects the internal state of the object.

class Person {
    private ssn: string;

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

    public getSSN(): string {
        return this.ssn;
    }
}

const person = new Person('123-45-6789');
console.log(person.getSSN());
// console.log(person.ssn);
  • ssn is private, preventing direct access from outside the class.
  • The public method getSSN provides controlled access to the private ssn property.

Output:

123-45-6789

3) Protected Access Modifier

The protected keyword is used to declare a class member so that it can be accessed by the class containing it and any of its subclasses, it comes handy when you want members of a class accessed in descendant classes but not outside.


class User {
    protected age: number;

    constructor(age: number) {
        this.age = age;
    }
}

class Employee extends User {
    public getRetirementAge(): number {
        return this.age + 65;
    }
}

const employee = new Employee(30);
console.log(employee.getRetirementAge());
//console.log(employee.age); 
  • age is protected, allowing access within User and its subclass Employee.
  • Attempting to access age directly from an instance of Employee results in an error.

Output:

95

Best Practice of Using Access Modifiers in TypeScript

  • Explicitly Define Access Modifiers: Always specify public, private, or protected for class members to enhance code clarity and maintainability.
  • Encapsulate Class Members: Use private or protected to restrict access to class properties and methods, ensuring internal implementation details are hidden.
  • Start with the Least Visible Modifier: Begin with private for class members and increase visibility only as necessary to maintain encapsulation.

Access Modifiers in TypeScript - FAQs

What happens if I don't specify an access modifier?

Class members are public by default, meaning they are accessible from anywhere.

Can I access a private member in a subclass?

No, private members are accessible only within the class they are defined.

What's the difference between protected and private access modifiers?

Protected members are accessible within the class and its subclasses, while private members are accessible only within the class they are defined.

How can I make a class property immutable?

Use the readonly modifier to ensure a property cannot be changed after initialization.

Is it necessary to use access modifiers in TypeScript?

While not mandatory, using access modifiers is a best practice to control access to class members, enhancing code encapsulation and maintainability.


Next Article

Similar Reads

three90RightbarBannerImg