Typescript class inheritence



我正在尝试扩展基类,并得到以下错误:

类"DerivedProduct"错误地扩展了基类"BaseProduct">
类型具有私有属性"route"的单独声明。

基类:

export class BaseProduct {
constructor(private route: ActivatedRoute, private store: Store<fromState>){}
}

派生类:

export class DerivedProduct extends BaseProduct {
constructor(private route: ActivatedRoute, private store: Store<fromState>){}
}

为什么我会出现此错误?

这些字段已经在基类中声明了,所以不需要重新声明它们(即不需要指定修饰符(。构造函数参数应该只是派生类中的参数,而不是字段。您还需要调用super构造函数

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)
}
}

注意您可以使用构造函数参数将额外的字段添加到字段语法糖中,但基本字段通常不应重新声明。如果您重新声明公共字段和受保护字段,它们通常不会引起问题,但不能重新声明为私有字段。

如果要从派生类访问这些字段,请将基类中的修饰符更改为protectedpublic

编辑

正如@seriesOne所指出的,如果你对构造函数没有任何额外的逻辑,你可以一起省略它,因为它将从基类继承

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.

在这两个构造函数中,您都在路由参数上使用关键字privateprivate route: ActivatedRoute。当您使用private关键字时,您实际上是在说构造函数中的参数也是类的成员。因此,BaseProduct有一个成员route,而您在DerivedProduct中也声明了相同的成员,这就是您出现错误的原因。

解决方案

在受BaseProduct保护的中建立路由

export class BaseProduct {
constructor(protected route: ActivatedRoute, protected store: Store<fromState>){}
}

然后在派生类中,不要使用private关键字,而是将参数传递给super类。

export class DerivedProduct extends BaseProduct {
constructor(route: ActivatedRoute, store: Store<fromState>){
super(route, store);
// this.route.doWhateverYouWantWithIt(this.store);....
}
}

您将可以作为基类和派生类的类成员访问routestore

最新更新