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.
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.
By default, all class members in TypeScript are public
. This means they can be accessed from anywhere.
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
name
and age
are public properties.greet
is a public method.Person
class.
John Doe
30
Hello, my name is John Doe and I am 30 years old.
A private
member is only accessible within the class that defines it. It cannot be accessed from outside the class or from any subclass.
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'.
name
and age
are private properties.getDetails
is a public method that provides access to the private properties.name
and age
directly from outside the Person
class results in a compilation error.
Name: John Doe, Age: 30
A protected
member is accessible within the class that defines it and within any subclass. It is not accessible from outside these classes.
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.
name
and age
are protected properties.getDetails
is a protected method.Employee
class extends Person
and can access the protected members.name
and age
directly from outside the Person
or Employee
class results in a compilation error.
Name: Jane Doe, Age: 28, Employee ID: 12345
TypeScript allows you to define access modifiers in constructor parameters, which automatically creates and initializes class members.
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'.
name
and age
parameters in the constructor are prefixed with private
, automatically creating private properties.Person
class.
Name: John Doe, Age: 30
The readonly
modifier makes a property immutable after its initial assignment.
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.
name
and age
properties are marked as readonly
, making them immutable after their initial assignment.
Name: John Doe, Age: 30
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.
employeeId
is a private property.name
is a protected property.department
is a public property.getEmployeeDetails
method provides access to the private and protected properties.
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 ! ❤️