How to solve the error “Types have separate declarations of a private property” in Typescript

"Types have separate declarations of a private property" in TypeScript

To fix the error “Types have separate declarations of a private property” in Typescript you can remove private modifier. So how to do it? Let’s go into detail now.

The reason for the error “Types have separate declarations of a private property” in Typescript

The error happens when some private property of a class is visible to other instances of that class which does not allow in Typescript.

Example of how the error happens:

class Account {
    constructor(private id: number, img: string, userName: string) {}
}
  
class DetailAccount extends Account {
    constructor(private id: number, img: string, userName: string) {
        super(id, img, userName);
    }
}

The error:

index.ts:7:7 - error TS2415: Class' DetailAccount' incorrectly extends base class 'Account'.
  Types have separate declarations of a private property 'id'.
7 class DetailAccount extends Account{
        ~~~~~~~~~~~~~

When I set ‘private’ to a property, it can only be accessed from within that class, but here I try to substitute the property to another so that I will get an error.

The solution for this error

Remove private modifier

You can remove the ‘private’ modifier to solve this error. Class’s properties have a ‘private’ modifier they can only access from within the class it is declared. So you can fix the error by removing the ‘private’ keyword to make the property visible.

Example:

class Account {
    constructor(private id: number, img: string, userName: string) {}
}
  
class DetailAccount extends Account {
    // Remove private modifier in subclasses property
    constructor(id: number, img: string, userName: string) {
        super(id, img, userName);
    }    
}

After removing the ‘private’ modifier, my id property can access from outside of the class it is declared.

Use protected modifier

The protected modifier allows you to access the property inside the class it declared and inside the subclasses.

Example:

class Account {
    // Using protected modifier
    constructor(protected id: number, img: string, userName: string) {}
}
  
class DetailAccount extends Account {
    constructor(id: number, img: string, userName: string) {
        super(id, img, userName);
    }
}

Here with the protected modifier, my subclasses DetailAccount can access to id property in the parent class Account.

Summary

In this article, I showed you how to solve the error “Types have separate declarations of a private property” in Typescript. If you want to access the property in the parent class, I recommend using the protected modifier for that property.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *