gpt4 book ai didi

angular - typescript 类继承

转载 作者:太空狗 更新时间:2023-10-29 17:44:14 24 4
gpt4 key购买 nike

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

Class 'DerivedProduct' incorrectly extends base class 'BaseProduct'.
Types have separate declarations of a private property '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)
}
}

注意 您可以使用构造函数参数向字段语法糖添加额外的字段,但通常不应重新声明基本字段。如果您重新声明公共(public)和 protected 字段,通常不会引起问题,但您不能重新声明私有(private)字段。

如果您想从派生类访问这些字段,请在基类中将修饰符更改为 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.

关于angular - typescript 类继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51500066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com