Developed By
Gautam Kumar - Full stack developer
DEEP DIVE INTO
In TypeScript, access modifiers—public, private, and protected—are used to control the visibility and accessibility of class members (properties and methods) within a class and its subclasses. They play a crucial role in enforcing encapsulation and managing the access to class members. Let's delve deeper into these access modifiers:
Default Modifier: If no access modifier is specified, members are considered public by default.
Accessible Everywhere: public members are accessible from inside the class, from instances of the class, and even from external sources.
javascriptclass Car {
public make: string;
public model: string;
constructor(make: string, model: string) {
this.make = make;
this.model = model;
}
public getInfo(): string {
return `Make: ${this.make}, Model: ${this.model}`;
}
}
Restricted Access: private members are only accessible within the class they are declared in.
Inaccessible from Outside: They cannot be accessed from outside the class or from instances of the class.
javascriptclass BankAccount {
private balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
private deduct(amount: number) {
this.balance -= amount;
}
}
Accessible in Subclasses: protected members are accessible within the class they are declared in and its subclasses (classes that inherit from it).
Not Accessible from Instances: They cannot be accessed from instances of the class directly.
javascriptclass Animal {
protected sound: string;
constructor(sound: string) {
this.sound = sound;
}
}
class Dog extends Animal {
makeSound() {
console.log(`The dog makes a ${this.sound} sound.`);
}
}
Access modifiers enforce encapsulation and control the visibility of class members.
public members allow broad access, private restricts access to the defining class only, and protected allows access within inheriting classes.
TypeScript's compiler enforces these access controls at compile-time, contributing to code reliability and maintainability.
public is commonly used for members meant to be accessible from outside the class.
private is useful for sensitive data or implementation details that should not be exposed outside the class.
protected is employed when a class's property or method needs to be accessed by subclasses.
Understanding and using access modifiers in TypeScript is fundamental for writing maintainable and secure object-oriented code, ensuring proper encapsulation and controlling the accessibility of class members based on specific design considerations.