TypeScript Access Modifiers

Access modifiers in TypeScript are used to control the visibility and accessibility of class members (properties and methods). They are crucial for implementing encapsulation, which is one of the key principles of object-oriented programming. TypeScript provides three primary access modifiers: public, private, and protected. In this chapter, we will explore each of these access modifiers in detail, from basic to advanced usage, with examples and explanations to ensure a comprehensive understanding.

Overview of Access Modifiers

What are Access Modifiers?

Access modifiers are keywords that define the access level of class members. They determine whether a member can be accessed from outside the class, within derived classes, or only within the class itself.

Types of Access Modifiers

  1. Public: The member is accessible from anywhere.
  2. Private: The member is accessible only within the class it is declared.
  3. Protected: The member is accessible within the class it is declared and its subclasses.

Public Access Modifier

By default, all class members in TypeScript are public. This means they can be accessed from anywhere.

Example

				
					class Person {
    public name: string;
    public age: number;

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

    public greet(): string {
        return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
    }
}

const john = new Person('John Doe', 30);
console.log(john.name); // Accessible
console.log(john.age);  // Accessible
console.log(john.greet()); // Accessible
				
			

Explanation:

  • name and age are public properties.
  • greet is a public method.
  • All members are accessible from outside the Person class.

Output:

				
					John Doe
30
Hello, my name is John Doe and I am 30 years old.
				
			

Private Access Modifier

A private member is only accessible within the class that defines it. It cannot be accessed from outside the class or from any subclass.

Example

				
					class Person {
    private name: string;
    private age: number;

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

    public getDetails(): string {
        return `Name: ${this.name}, Age: ${this.age}`;
    }
}

const john = new Person('John Doe', 30);
console.log(john.getDetails()); // Accessible
// console.log(john.name); // Error: Property 'name' is private and only accessible within class 'Person'.
// console.log(john.age); // Error: Property 'age' is private and only accessible within class 'Person'.

				
			

Explanation:

  • name and age are private properties.
  • getDetails is a public method that provides access to the private properties.
  • Attempting to access name and age directly from outside the Person class results in a compilation error.

Output:

				
					Name: John Doe, Age: 30
				
			

Protected Access Modifier

A protected member is accessible within the class that defines it and within any subclass. It is not accessible from outside these classes.

Example

				
					class Person {
    protected name: string;
    protected age: number;

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

    protected getDetails(): string {
        return `Name: ${this.name}, Age: ${this.age}`;
    }
}

class Employee extends Person {
    private employeeId: number;

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

    public getEmployeeDetails(): string {
        return `${this.getDetails()}, Employee ID: ${this.employeeId}`;
    }
}

const jane = new Employee('Jane Doe', 28, 12345);
console.log(jane.getEmployeeDetails()); // Accessible
// console.log(jane.name); // Error: Property 'name' is protected and only accessible within class 'Person' and its subclasses.
// console.log(jane.age); // Error: Property 'age' is protected and only accessible within class 'Person' and its subclasses.
				
			

Explanation:

  • name and age are protected properties.
  • getDetails is a protected method.
  • Employee class extends Person and can access the protected members.
  • Attempting to access name and age directly from outside the Person or Employee class results in a compilation error.

Output:

				
					Name: Jane Doe, Age: 28, Employee ID: 12345
				
			

Advanced Usage of Access Modifiers

Access Modifiers in Constructor Parameters

TypeScript allows you to define access modifiers in constructor parameters, which automatically creates and initializes class members.

Example

				
					class Person {
    constructor(private name: string, private age: number) {}

    public getDetails(): string {
        return `Name: ${this.name}, Age: ${this.age}`;
    }
}

const john = new Person('John Doe', 30);
console.log(john.getDetails()); // Accessible
// console.log(john.name); // Error: Property 'name' is private and only accessible within class 'Person'.
// console.log(john.age); // Error: Property 'age' is private and only accessible within class 'Person'.
				
			

Explanation:

  • The name and age parameters in the constructor are prefixed with private, automatically creating private properties.
  • These private properties are accessible only within the Person class.

Output:

				
					Name: John Doe, Age: 30
				
			

Readonly Access Modifier

The readonly modifier makes a property immutable after its initial assignment.

Example

				
					class Person {
    public readonly name: string;
    public readonly age: number;

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

    public getDetails(): string {
        return `Name: ${this.name}, Age: ${this.age}`;
    }
}

const john = new Person('John Doe', 30);
console.log(john.getDetails()); // Accessible
// john.name = 'Jane Doe'; // Error: Cannot assign to 'name' because it is a read-only property.
// john.age = 31; // Error: Cannot assign to 'age' because it is a read-only property.
				
			

Explanation:

  • The name and age properties are marked as readonly, making them immutable after their initial assignment.
  • Attempting to modify these properties results in a compilation error.

Output:

				
					Name: John Doe, Age: 30
				
			

Combining Access Modifiers

Example

				
					class Employee {
    private employeeId: number;
    protected name: string;
    public department: string;

    constructor(employeeId: number, name: string, department: string) {
        this.employeeId = employeeId;
        this.name = name;
        this.department = department;
    }

    public getEmployeeDetails(): string {
        return `ID: ${this.employeeId}, Name: ${this.name}, Department: ${this.department}`;
    }
}

const employee = new Employee(12345, 'Alice', 'HR');
console.log(employee.getEmployeeDetails()); // Accessible
console.log(employee.department); // Accessible
// console.log(employee.employeeId); // Error: Property 'employeeId' is private and only accessible within class 'Employee'.
// console.log(employee.name); // Error: Property 'name' is protected and only accessible within class 'Employee' and its subclasses.
				
			

Explanation:

  • employeeId is a private property.
  • name is a protected property.
  • department is a public property.
  • The getEmployeeDetails method provides access to the private and protected properties.

Output:

				
					ID: 12345, Name: Alice, Department: HR
HR
				
			

We explored TypeScript's access modifiers: public, private, and protected. These modifiers help you control the visibility and accessibility of class members, enabling encapsulation and maintaining the integrity of your code. We covered the basic usage of each access modifier with detailed examples and explanations, as well as advanced topics like access modifiers in constructor parameters, the readonly modifier, and combining access modifiers. Happy coding ! ❤️

Table of Contents