[英]TS2322 Property missing in subclass, but it's there
我有这两个Angular 4组件类。
超类:
export class SectionComponent implements OnInit {
slides: SlideComponent[];
constructor() {
}
ngOnInit() {
}
}
和子类:
export class FrontPageSectionComponent extends SectionComponent implements OnInit {
slides: SlideComponent[];
constructor() {
super();
}
ngOnInit() {
this.slides = [];
}
}
我尝试在AppComponent中创建一个超类数组...
export class AppComponent implements OnInit {
sections: SectionComponent[];
constructor() {
}
ngOnInit(): void {
this.sections = [
FrontPageSectionComponent
];
}
}
但是我得到一个错误:
TS2322:类型'typeof FrontPageSectionComponent []'无法分配给类型'SectionComponent []'。 类型“ typeof FrontPageSectionComponent”不能分配给类型“ SectionComponent”。 类型“ typeof FrontPageSectionComponent”中缺少属性“ slides”。
我自己尚未指定任何类型,并且在代码库中搜索“ typeof FrontPageSectionComponent”不会产生任何结果,因此我认为这是TypeScript推断。
你的数组
sections: SectionComponent[];
声明SectionComponent
实例的数组。
如果要声明从SectionComponent
派生的类的数组,实际上可以。
您需要使用类值的类型,而不是其实例的类型。
要获取值的类型,请使用typeof
关键字。
const c: typeof SectionComponent = SectionComponent;
因此,要声明一组构成SectionComponent
实例的类,您将编写它们。
sections: Array<typeof SectionComponent>;
更抽象地讲,您可以编写
sections: Array<new () => SectionComponent>;
这样的技术在高阶编程中非常有用。
注意我在嵌套时纯粹是为了清晰起见使用Array<...>
语法, []
也可以使用
当我代替FrontPageComponent
将new FrontPageComponent()
插入数组时,它起作用了。
因此,我想起了有关Angular的一些知识,他们知道如何构造它们,现在我这样做了:
export class AppComponent implements OnInit {
sections: SectionComponent[];
constructor(private frontPage: FrontPageSectionComponent) {
}
ngOnInit(): void {
this.sections = [
this.frontPage,
];
}
}
错误消失了。 如果这仍然是错误的做法,请告诉我。
我实际上是将这些部分移到SectionService来分离问题((构造函数会很快填满)),但是由于我在Google上搜索时没有发现任何好的结果,所以我提出了这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.