Last updated: Feb 28, 2024
Reading timeยท2 min
The error "Property is private and only accessible within class" occurs when
we try to access a private
property outside of a class.
To solve the error, declare the class property as public
if you need to
access it from outside the class.
Here is an example of how the error occurs.
class Employee { // ๐๏ธ private if you need to access only from inside this class private salary: number = 100; logSalary() { console.log(this.salary); } } const employee = new Employee(); // โ๏ธ Error: Property 'salary' is private and // only accessible within class 'Employee'.ts(2341) employee.salary; console.log(employee.logSalary()); // ๐๏ธ 100
The salary
property has
private
member visibility, so it can only be accessed from within the Employee
class.
public
To solve the error, assign the property with public
visibility.
class Employee { // ๐๏ธ public if you need to access from outside the class public salary: number = 100; } const employee = new Employee(); console.log(employee.salary); // ๐๏ธ 100
Class properties have public visibility by default. Public members can be accessed from anywhere.
The same approach can be used when declaring a constructor function's parameters.
class Employee { // ๐๏ธ public if you need to access from outside the class constructor(public salary: number) { this.salary = salary; } } const employee = new Employee(200); console.log(employee.salary); // ๐๏ธ 200
If you set the class property to have private
visibility in the constructor,
it can only be accessed from inside the class.
class Employee { // ๐๏ธ should be public if you need to access // from outside the class constructor(private salary: number) { this.salary = salary; } } const employee = new Employee(200); // โ๏ธ Error: Property 'salary' is private and only accessible within class 'Employee'.ts(2341) console.log(employee.salary);
You might also get this error when using class properties with protected visibility.
class Employee { // ๐๏ธ protected constructor(protected salary: number) { this.salary = salary; } } const employee = new Employee(200); // โ๏ธ Property 'salary' is protected and only accessible // within class 'Employee' and its subclasses.ts(2445) console.log(employee.salary);
Protected properties can only be accessed from within the class and its subclasses.
You can learn more about the related topics by checking out the following tutorials: