In TypeScript, the private
access modifier, which makes a member visible only within its containing class, is a key concept in the world of object-oriented programming.
The private
access modifier restricts the visibility of a member (such as a property or a method) to the class that contains it. This means that when a member is marked as private
, it cannot be accessed from outside of its containing class, or from subclasses of its containing class.
Let's try to understand this with an example:
class Employee {
private employeeName: string;
constructor(name: string) {
this.employeeName = name;
}
getEmployeeName() {
return this.employeeName;
}
}
In this example, employeeName
is a private member of the Employee
class. It can only be accessed within the Employee
class. Trying to access it directly from an object of the Employee
class would lead to a compilation error.
let emp = new Employee("John Doe");
console.log(emp.employeeName); // Error: 'employeeName' is private and only accessible within class 'Employee'.
However, employeeName
can be accessed through the getEmployeeName()
method in the Employee
class.
console.log(emp.getEmployeeName()); // 'John Doe'
Using private
is a good practice as it encapsulates the data of the class and protects it from being altered directly. It enforces a strict level of security and control over how the variables and functions can be used, ensuring that the code is used as intended.
It's worth noting that JavaScript doesn't natively support private
visibility. TypeScript adds this functionality as part of its additional static type-checking and class-based object-oriented programming capabilities. Once transpiled to JavaScript, the private
modifier does not exist, and access is not restricted during runtime. This is purely a compile-time construct.
Mastering access modifiers is a step forward in achieving clean and safe TypeScript code. Use them wisely and you’ll have a much better organized codebase.