Access Modifiers in TypeScript
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.
- Public: Members are accessible from anywhere; this is the default modifier if none is specified.
- Private: Members are accessible only within the class they are defined in.
- Protected: Members are accessible within the class they are defined in and in subclasses.
Now let's understand this with the help of example:
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:
Buddy
Buddy is a Dog.
Buddy is a Dog and is 3 years old.
In this example:
- name is public: accessible from anywhere.
- age is private: accessible only within the Animal class.
- species is protected: accessible within Animal and its subclass Dog.
Types of Access Modifiers
1) Public Access Modifier
The public modifier allows class members to be accessible from anywhere. By default, all class members are public if no access modifier is specified.
Now let's understand this with the help of example:
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:
Dog
Dog makes a sound.
In this example:
- name and makeSound are public, allowing access from outside the class.
- We can create an instance of Animal and access its name property and makeSound method directly.
2. Private Access Modifier
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.
Now let's understand this with the help of example:
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-6789
In this example:
- ssn is private, preventing direct access from outside the class.
- The public method getSSN provides controlled access to the private ssn property.
3) 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.
Now let's understand this with the help of example:
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:
95
In this example:
- age is protected, allowing access within User and its subclass Employee.
- Attempting to access age directly from an instance of Employee results in an error.
4. Read-only Access Modifier in Typescript
After initialization, the read-only access modifier marks a property as immutable, enabling it to be read but not directly updated. This improves data security and makes state management easier.
Example 1: Read-only property in a class
class User {
readonly id: number;
constructor(id: number) {
this.id = id;
}
}
const user = new User(101);
console.log(user.id); // 101
// user.id = 102; // Error: Cannot assign to 'id' because it is a read-only property
Output
101
In this example:
- The class User has a readonly property id.
- The constructor sets id to 101.
- console.log(user.id) prints 101.
- Trying to change id would cause a compile-time error.
Example 2: Read-only property with public modifier
class Product {
constructor(public readonly name: string) {}
}
const product = new Product('Laptop');
console.log(product.name); // Laptop
// product.name = 'Tablet'; // Error: Cannot assign to 'name' because it is read-only
Output
Laptop
In this example:
- The class Product has a readonly property name set via the constructor.
- Creating new Product('Laptop') sets name to "Laptop".
- console.log(product.name) prints Laptop.
- Attempting to change name would cause a compile-time error.