Borislav Hadzhiev
Mon Mar 14 2022·2 min read
Photo by Armando Castillejos
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.
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 declare 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.