【问题标题】:Typescript class inheritence打字稿类继承
【发布时间】:2018-07-24 13:36:51
【问题描述】:

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

“DerivedProduct”类错误地扩展了基类“BaseProduct”。
类型具有私有属性“路由”的单独声明。

基类:

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

派生类:

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

为什么会出现这个错误?

【问题讨论】:

  • 附带说明:我想错误应该是 ... DerivedProduct .. 而不是 DerivedClass,不是吗?

标签: angular typescript


【解决方案1】:

字段已在基类中声明,因此您无需重新声明它们(即无需指定修饰符)。构造函数参数应该只是派生类中的参数,而不是字段。你还需要调用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

编辑

正如@series0ne 指出的那样,如果您对构造函数没有任何额外的逻辑,则可以将其全部省略,因为它将继承自基类:

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.

【讨论】:

  • 投反对票的人可以评论一下原因吗?没有判断力只是想知道为什么你认为答案不好..
  • 我不是投反对票的人,我刚刚再次投了赞成票,因为你是对的。不过,如果我是你,我可能会添加一些“如果派生类中的构造函数逻辑相同,则可以完全省略派生类中的构造函数声明”
  • @Dave 原始版本没有将它们公开,它使它们对基类保持私有。
  • @Dave 未在派生构造函数上指定访问修饰符不会使它们成为公共字段,而是使它们成为简单的参数。将字段保留为基类私有可能是一种合理的方法,仅使用提供的示例很难说。
  • 谢谢,但是如果我不指定修饰符,那么参数是公共的还是私有的,以及如何从基础使用它们,因为它们被标记为私有?派生类可以访问基类的私有属性吗?
【解决方案2】:

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

解决方案

BaseProductprotected 中创建路由

 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 作为基类和派生类中的类成员。

【讨论】:

    猜你喜欢
    • 2017-12-04
    • 2020-05-07
    • 2017-07-14
    • 2016-12-05
    • 2017-04-10
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多