Borislav Hadzhiev
Last updated: Mar 25, 2022
Check out my new book
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.
Here is an example of how the error occurs.
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.
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
.
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.
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
.