I am trying to extend a base class and getting the following error:
Class 'DerivedProduct' incorrectly extends base class 'BaseProduct'.
Types have separate declarations of a private property 'route'.
Base Class:
export class BaseProduct {
constructor(private route: ActivatedRoute, private store: Store<fromState>){}
}
Derived Class:
export class DerivedProduct extends BaseProduct {
constructor(private route: ActivatedRoute, private store: Store<fromState>){}
}
Why am I getting this error?
The fields are already declared in the base class so you don't need to redeclare them (ie no need to specify the modifier). Constructor arguments should just be arguments in the derived class and not fields. You also need to call the super
constructor
export class BaseProduct {
constructor(private route: ActivatedRoute, private store: Store<fromState>) { }
}
export class DerivedProduct extends BaseProduct {
constructor(route: ActivatedRoute, store: Store<fromState>) {
super(route, store)
}
}
Note You could add extra fields using the constructor argument to field syntactic sugar but the base fields should not generally be re-declared. Public and protected fields generally would not cause issues if you re-declared them but you can't re-declared privates.
If you want to access those fields from the derived class change the modifier to protected
or public
in the base class.
Edit
As @series0ne points out if you don't have any extra logic to the constructor you can omit it all together, as it will be inherited from the base class:
export class BaseProduct {
constructor(private route: ActivatedRoute, private store: Store<fromState>) { }
}
export class DerivedProduct extends BaseProduct {
}
new DerivedProduct(route, store); //Works, also Angular should see it like this as well.
In both constructors, you use the keyword private on the route parameter. private route: ActivatedRoute
.
When you use the private
keyword, you are essentially saying that parameter in the constructor is also a member of your class. Thus BaseProduct
has a member route
, and you are also declaring the same in your DerivedProduct
, which is why you are having the error.
Solution
Make route in BaseProduct
protected
export class BaseProduct {
constructor(protected route: ActivatedRoute, protected store: Store<fromState>){}
}
Then in your derived class, do not use the private keyword, rather pass in your parameters to the super
class.
export class DerivedProduct extends BaseProduct {
constructor(route: ActivatedRoute, store: Store<fromState>){
super(route, store);
// this.route.doWhateverYouWantWithIt(this.store);....
}
}
You will have access to both route
and store
as class members in both base and derived classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With