Last Updated : 14 Jun, 2025
In TypeScript, access modifiers control the visibility and accessibility of class members, such as properties and methods, aligning with the principles of encapsulation and information hiding in object-oriented programming.
class Animal {
public name: string;
private age: number;
protected species: string;
constructor(name: string, age: number, species: string) {
this.name = name;
this.age = age;
this.species = species;
}
public getInfo(): string {
return `${this.name} is a ${this.species}.`;
}
// Adding the getAge method to access the private age property
public getAge(): number {
return this.age;
}
}
class Dog extends Animal {
constructor(name: string, age: number) {
super(name, age, 'Dog');
}
public getDetails(): string {
// Accessing age through the getAge method
return `${this.name} is a ${this.species} and is ${this.getAge()} years old.`;
}
}
const myDog = new Dog('Buddy', 3);
console.log(myDog.name); // Accessible
console.log(myDog.getInfo()); // Accessible
console.log(myDog.getDetails()); // Accessible
Output:
BuddyTypes of Access Modifiers 1) Public Access Modifier
Buddy is a Dog.
Buddy is a Dog and is 3 years old.
The public modifier allows class members to be accessible from anywhere. By default, all class members are public if no access modifier is specified.
JavaScript
class Animal {
public name: string;
constructor(name: string) {
this.name = name;
}
public makeSound(): void {
console.log(`${this.name} makes a sound.`);
}
}
const dog = new Animal('Dog');
console.log(dog.name); // Accessible
dog.makeSound(); // Accessible
Output:
Dog2. Private Access Modifier
Dog makes a sound.
The private modifier restricts access to class members, making them accessible only within the class they are defined. This ensures encapsulation and protects the internal state of the object.
JavaScript
class Person {
private ssn: string;
constructor(ssn: string) {
this.ssn = ssn;
}
public getSSN(): string {
return this.ssn;
}
}
const person = new Person('123-45-6789');
console.log(person.getSSN());
// console.log(person.ssn);
Output:
123-45-67893) Protected Access Modifier
The protected keyword is used to declare a class member so that it can be accessed by the class containing it and any of its subclasses, it comes handy when you want members of a class accessed in descendant classes but not outside.
JavaScript
class User {
protected age: number;
constructor(age: number) {
this.age = age;
}
}
class Employee extends User {
public getRetirementAge(): number {
return this.age + 65;
}
}
const employee = new Employee(30);
console.log(employee.getRetirementAge());
//console.log(employee.age);
Output:
95Best Practice of Using Access Modifiers in TypeScript
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4