Ang*_*gad 4 typescript angular
我试图扩展基类并得到以下错误:
类'DerivedProduct'错误地扩展了基类'BaseProduct'.
类型具有私有属性"路由"的单独声明.
基类:
 export class BaseProduct {
    constructor(private route: ActivatedRoute, private store: Store<fromState>){}
   }
Run Code Online (Sandbox Code Playgroud)
派生类:
export class DerivedProduct extends BaseProduct {
  constructor(private route: ActivatedRoute, private store: Store<fromState>){}
}
Run Code Online (Sandbox Code Playgroud)
为什么我收到此错误?
这些字段已在基类中声明,因此您无需重新声明它们(即无需指定修饰符).构造函数参数应该只是派生类中的参数而不是字段.您还需要调用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)
    }
}
Run Code Online (Sandbox Code Playgroud)
注意您可以使用构造函数参数向字段语法糖添加额外字段,但通常不应重新声明基本字段.公共和受保护的字段通常不会导致问题,如果您重新声明它们,但您不能重新声明私有.
如果要从派生类访问这些字段,请将修改器更改为基类protected或public基类.
编辑
正如@ 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.
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           113 次  |  
        
|   最近记录:  |