在打字稿中定义抽象类的类型
如何让typeof BaseListComponent
低于可指定的?在打字稿中定义抽象类的类型
下面的代码引发以下错误:
Type '
({ title: string; component: typeof QuestionsListComponent; } | { title: string; component: ...'
is not assignable to type'{ title: string; component: typeof BaseListComponent; }[]'
.
摘录:
abstract class BaseListComponent {
protected title
}
class WeatherListComponent extends BaseListComponent {}
class QuestionsListComponent extends BaseListComponent {}
let containerItems: Array<{title: string, component: typeof BaseListComponent}>;
containerItems = [
{title:'TypeScript', component: QuestionsListComponent},
{title:'Angular2', component: QuestionsListComponent},
{title:'Weather', component: WeatherListComponent}
]
P.S这是从一个角度应用的简化的摘录等有这种疯狂背后的逻辑。
采用了棱角分明的Type
界面解决方案。 Type
可以找到更好的解释here。步骤来解决:
进口
Type
像这样:import { Type } from "@angular/core";
更换
typeof BaseListComponent
与Type<BaseListComponent>
对于人来这里谁不使用的角度,this thread可能会有所帮助。
我可能是错的,但是,这不是component: typeof BaseListComponent
宣布component
是Type
型
应该不是只是component: BaseListComponent
感谢您的回答:它会导致错误:'Type'({title:string; component:typeof QuestionsContainerComponent;} | {title:string; component:... '不能分配给类型'{title:string; component:BaseListContainerComponent;} []'。' – Tom
在您的示例中,“BaseListContainerComponent”与“BaseListComponent”不同。您的示例在[TypeScript Playground](https://www.typescriptlang.org/play/)中适用于我。 – Raven
对不起,我简化了名字,但忘了在错误信息中也这么做。这真是奇怪,它不能在角度环境中工作,但它在操场上...... – Tom
在您的错误消息中,您试图将“OR”类型(“{} | {}”)分配给数组('{...} []') – Raven