How To Fix ‘#’ is defined as property in class ‘##’ but is overridden here in ‘###’ as an accessor

The error ‘#’ is defined as property in class ‘##’ but is overridden here in ‘###’ as an accessor occurs because we override a property declared in the parent class. This article will show you how to fix it.

Why does the error ‘#’ is defined as property in class ‘##’ but is overridden here in ‘###’ as an accessor occur

When you declare a property in the parent class, this property will appear in the child classes. The error will appear when you treat this property as a method and proceed to override it. This is a new error checking mechanism that appeared in TypeScript version 4

Error Example:

class Vehicle {
    manufacturer = "";
    engine = "";
}

class Car extends Vehicle {
    brand = "";

    // Override a property declared in the parent class
    get manufacturer() {
        return this.brand;
    }
    set manufacturer(brand: string) {
        this.brand = brand;
    }
}

Error Output:

'manufacturer' is defined as a property in the class 'Vehicle' but is overridden here in 'Car' as an accessor.

In the above code, we have two classes, Vehicle, and Car, in which class Car extends class Vehicle, so class Vehicle is the parent class and class Car is the child class. Inside the Vehicle class, we have declared an attribute as manufacturer. The child class after extending the parent class, already has this property, but we use the property as a method and override it. And so the error appeared.

How to solve the error ‘#’ is defined as property in class ‘##’ but is overridden here in ‘###’ as an accessor

It’s common practice in programming languages that if you come from a parent, you specify a different property or function, and you can’t use it unless you remove the old one, but it should be the same. You can make these changes:

class Vehicle {
    manufacturer = "";
    engine = "";
}

class Car extends Vehicle {
    _brand = "";

    // Use a different method name that does not match the property name declared in the parent class
    get brand() {
        return this._brand;
    }
    set brand(brand: string) {
        this._brand = brand;
    }
}

We will use a different name for the two get and set methods to avoid overlapping with the manufacturer attribute declared in the parent class.

Summary

Through the article, we have found the cause of the ‘#’ is defined as property in class ‘##’ but is overridden here in ‘###’ as an accessor. The way to avoid this error is effortless. We need to make sure that we don’t override a property declared in the parent class. Hope you get it fixed soon.

Leave a Reply

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