Access modifiers in TypeScript are keywords that determine the visibility and accessibility of class members (properties and methods). There are three access modifiers available in TypeScript:
1. Public
2. Private
3. Protected
By default, all class members are assumed to be public if no access modifier is specified.
Let’s discuss each of these access modifiers with their roles in class properties and methods.
1. ‘public‘: The ‘public‘ modifier allows a class member (property or method) to be accessible everywhere. You can access a public member within the class itself, in derived classes, and anywhere outside the class.
Here’s an example:
class MyClass {
public property: number;
public method(): void {
console.log("This is a public method.");
}
}
const obj = new MyClass();
// Accessible outside the class
obj.property = 5;
obj.method();
2. ‘private‘: The ‘private‘ modifier restricts access to the class member to within the class itself. This means that you cannot access a private property or method from derived classes or outside the class.
Example:
class MyClass {
private property: number;
private method(): void {
console.log("This is a private method.");
}
}
const obj = new MyClass();
// Not accessible outside the class
// obj.property = 5; // Error: Property 'property' is private and only accessible within class 'MyClass'.
// obj.method(); // Error: Property 'method' is private and only accessible within class 'MyClass'.
3. ‘protected‘: The ‘protected‘ modifier is similar to ‘private‘. A protected class member is only accessible within the class and any derived classes. This means that you cannot access a protected member from outside the class.
Example:
class MyClass {
protected property: number;
protected method(): void {
console.log("This is a protected method.");
}
}
class DerivedClass extends MyClass {
public printPropertyAndMethod(): void {
console.log("Property:", this.property);
this.method();
}
}
const obj = new DerivedClass();
// Accessible in the derived class
obj.printPropertyAndMethod();
// Not accessible outside the class
// obj.property = 5; // Error: Property 'property' is protected and only accessible within class 'MyClass' and its subclasses.
// obj.method(); // Error: Property 'method' is protected and only accessible within class 'MyClass' and its subclasses.
In conclusion, access modifiers in TypeScript play an important role in determining the accessibility and visibility of class members. They help encapsulate and manage the internal state and behavior of a class.