Understanding Access Modifiers in TypeScript
Learn how to use the public access modifier in TypeScript to control the visibility of class members. Explore its default behavior, accessibility, and impact on code organization and encapsulation.
Access Modifiers
TypeScript offers access modifiers to control the visibility of class members, enhancing encapsulation and code organization.
Public Access Modifier
Default behavior: All members are public by default if no access modifier is specified.
Accessibility: Members can be accessed from anywhere, including within the class, derived classes, and outside the class.
Example:
Syntax
class Employee {
public empCode: number; // Explicitly public
empName: string; // Implicitly public
}
Private Access Modifier
Accessibility: Members are accessible only within the declaring class.
Encapsulation: Protects data integrity by preventing external modification.
Example:
Syntax
class Employee {
private empId: number;
constructor(id: number) {
this.empId = id;
}
}
Protected Access Modifier
Accessibility: Members are accessible within the declaring class and its derived classes.
Inheritance: Used to share data and behavior among related classes.
Example:
Syntax
class Person {
protected name: string;
constructor(name: string) {
this.name = name;
}
}
class Employee extends Person {
// Can access and modify name here
}
Additional Modifiers
- readonly: Prevents modification of a property after its initialization.
- static: Defines a member that belongs to the class itself, rather than individual instances.
Example:
Syntax
class MathUtils {
static PI = 3.14159; // Static property
}
Best Practices
- Use
private
for data that should be encapsulated within the class. - Use
protected
for data shared among related classes. - Use
public
for members that need to be accessed from outside the class. - Consider using
readonly
for properties that should not be modified after initialization. - Use
static
members for constants or utility methods that don't require instance context.
By effectively utilizing access modifiers, you can create well-structured, maintainable, and secure TypeScript classes.