Property is private and only accessible within class in TS

avatar

Borislav Hadzhiev

Last updated: Mar 14, 2022

banner

Photo from Unsplash

Property is private and only accessible within class in TS #

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.

index.ts
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.

index.ts
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.

index.ts
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.

index.ts
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.

index.ts
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.

Conclusion #

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.