'X' is defined as property in class 'Y' but is overridden here in 'Z' as an accessor

avatar

Borislav Hadzhiev

Last updated: Mar 25, 2022

banner

Check out my new book

'X' is defined as property in class 'Y' but is overridden here in 'Z' as an accessor #

The error "'X' is defined as a property in class 'Y', but is overridden here in 'Z' as an accessor" occurs when a property overrides an accessor or vice versa in a derived class. To solve the error, use properties or accessors in both classes for the members you need to override.

defined as property in class but overridden

Here is an example of how the error occurs.

index.ts
class Person { name = ''; country = ''; } class Developer extends Person { _name = ''; // ⛔️ Error: 'name' is defined as a property in class 'Person', // but is overridden here in 'Developer' as an accessor.ts(2611) get name() { return this._name; } set name(str: string) { this._name = str; } }

The Person class has a name property.

The Developer class extends from Person, but overrides the name property using accessors (getter and setter).

Since TypeScript 4.0, it's an error for properties to override accessors or vice versa.

In our example, the Developer class tries to override the name property of the Person class with accessors.

The name accessors in the Developer class basically shadow the name property in the Person class.

To solve the error in this situation, we can update the parent class to also use accessors for name.

index.ts
class Person { _name = ''; get name() { return this._name; } set name(str: string) { this._name = str; } country = ''; } class Developer extends Person { _newName: any; get name() { return this._newName; } set name(str: string) { this._newName = str; } }

We are able to override an accessor using another accessor in a derived class.

In the same way, we are able to override a property with a property in a derived class, as long as the type of the property is compatible with its type in the parent.

Note that the type of your accessors have to be compatible between the classes.

If you have to change the type of a parameter or the return type of an accessor, you can turn off type checking, by setting the type to any.

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.