Access modifiers are a crucial feature in TypeScript that control the visibility and accessibility of class members. They play a vital role in enforcing encapsulation, a key principle of object-oriented programming.
TypeScript provides three main access modifiers:
By default, all class members in TypeScript are public. You can explicitly use the public
keyword for clarity:
class Employee {
public name: string;
public constructor(name: string) {
this.name = name;
}
public displayName(): void {
console.log(this.name);
}
}
Public members can be accessed from anywhere, including outside the class.
The private
modifier restricts access to the containing class. This is useful for hiding internal implementation details:
class BankAccount {
private balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
public deposit(amount: number): void {
this.balance += amount;
}
public getBalance(): number {
return this.balance;
}
}
const account = new BankAccount(1000);
account.deposit(500);
console.log(account.getBalance()); // 1500
// console.log(account.balance); // Error: Property 'balance' is private
In this example, balance
is private, ensuring it can only be modified through the class methods.
The protected
modifier allows access within the class and its subclasses, facilitating inheritance while maintaining encapsulation:
class Person {
protected name: string;
constructor(name: string) {
this.name = name;
}
}
class Employee extends Person {
private department: string;
constructor(name: string, department: string) {
super(name);
this.department = department;
}
public getEmployeeDetails(): string {
return `${this.name} works in ${this.department}`;
}
}
const emp = new Employee("John Doe", "IT");
console.log(emp.getEmployeeDetails()); // John Doe works in IT
// console.log(emp.name); // Error: Property 'name' is protected
Here, name
is accessible in both Person
and Employee
classes, but not outside them.
private
for internal implementation detailsprotected
for members that should be accessible in subclassespublic
for members that need to be accessed from outside the classTo deepen your understanding of TypeScript's object-oriented features, explore these related topics:
By mastering access modifiers, you'll be able to create more robust and maintainable TypeScript code, leveraging the full power of object-oriented programming principles.