Access Modifiers in TypeScript
Access modifiers in TypeScript allow you to control the visibility of class members. They help you define how and where class members can be accessed, ensuring encapsulation and enhancing code maintainability. This guide covers the primary access modifiers available in TypeScript: public
, private
, and protected
.
Public
The public
modifier is the default in TypeScript. Members marked as public
can be accessed from anywhere:
class Animal {
public name: string;
constructor(name: string) {
this.name = name;
}
public move(distance: number): void {
console.log(`${this.name} moved ${distance} meters.`);
}
}
const cat = new Animal("Cat");
cat.name = "Tom"; // Accessible
cat.move(10); // Accessible
Private
The private
modifier restricts access to members so that they can only be accessed within the class they are defined in:
class Animal {
private name: string;
constructor(name: string) {
this.name = name;
}
public move(distance: number): void {
console.log(`${this.name} moved ${distance} meters.`);
}
}
const cat = new Animal("Cat");
// cat.name = "Tom"; // Error: Property 'name' is private and only accessible within class 'Animal'.
cat.move(10); // Accessible
Protected
The protected
modifier allows access to members within the class and its subclasses but not from outside these classes:
class Animal {
protected name: string;
constructor(name: string) {
this.name = name;
}
protected move(distance: number): void {
console.log(`${this.name} moved ${distance} meters.`);
}
}
class Bird extends Animal {
constructor(name: string) {
super(name);
}
public fly(distance: number): void {
this.move(distance); // Accessible within subclass
console.log(`${this.name} flew ${distance} meters.`);
}
}
const parrot = new Bird("Parrot");
// parrot.name = "Polly"; // Error: Property 'name' is protected and only accessible within class 'Animal' and its subclasses.
parrot.fly(15); // Accessible
Readonly
Additionally, TypeScript provides the readonly
modifier for properties that should only be assigned during initialization:
class Animal {
readonly name: string;
constructor(name: string) {
this.name = name;
}
public move(distance: number): void {
console.log(`${this.name} moved ${distance} meters.`);
}
}
const dog = new Animal("Dog");
// dog.name = "Rex"; // Error: Cannot assign to 'name' because it is a read-only property.
dog.move(20); // Accessible
Conclusion
Access modifiers in TypeScript provide a robust mechanism for controlling the visibility and accessibility of class members. By using public
, private
, and protected
access modifiers appropriately, you can create well-encapsulated and maintainable code. Additionally, the readonly
modifier helps you enforce immutability for certain properties, adding an extra layer of protection to your classes.
Comments
Post a Comment