Access modifiers in TypeScript are keywords that set the accessibility of classes, properties, methods, and constructors. They determine whether a class member can be accessed from outside the class. TypeScript provides three primary access modifiers:
Public: This is the default modifier. Members with the public
modifier are accessible from anywhere.
Private: Members with the private
modifier are accessible only within the class they are defined in.
Protected: Members with the protected
modifier are accessible within the class they are defined in and in derived classes (subclasses).
Example of Access Modifiers
Here’s a detailed example demonstrating the use of public
, private
, and protected
access modifiers:
class Animal {
// Public property
public name: string;
// Private property
private age: number;
// Protected property
protected species: string;
// Constructor with public and private properties
constructor(name: string, age: number, species: string) {
this.name = name;
this.age = age;
this.species = species;
}
// Public method
public getName(): string {
return this.name;
}
// Private method
private getAge(): number {
return this.age;
}
// Protected method
protected getSpecies(): string {
return this.species;
}
}
class Dog extends Animal {
constructor(name: string, age: number, species: string) {
super(name, age, species);
}
// Public method accessing protected property
public getDetails(): string {
return `Name: ${this.name}, Species: ${this.species}`;
}
// Public method trying to access private property (will cause an error)
public tryToGetAge(): number {
// return this.age; // Error: Property 'age' is private and only accessible within class 'Animal'.
return 0; // Placeholder
}
}
const animal = new Animal("Lion", 5, "Panthera leo");
console.log(animal.name); // Accessible
// console.log(animal.age); // Error: Property 'age' is private and only accessible within class 'Animal'.
// console.log(animal.species); // Error: Property 'species' is protected and only accessible within class 'Animal' and its subclasses.
const dog = new Dog("Buddy", 3, "Canis lupus familiaris");
console.log(dog.getName()); // Accessible
console.log(dog.getDetails()); // Accessible
// console.log(dog.getSpecies()); // Error: Property 'getSpecies' is protected and only accessible within class 'Animal' and its subclasses.
Summary
Public:
- Accessible from anywhere.
- Default if no modifier is specified.
- Example:
public name: string;
Private:
- Accessible only within the class where it is defined.
- Example:
private age: number;
Protected:
- Accessible within the class and its subclasses.
- Example:
protected species: string;
These access modifiers help in implementing encapsulation and protecting the internal state and behavior of objects in TypeScript.