在打字稿中定义抽象类的类型

问题描述:

如何让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这是从一个角度应用的简化的摘录等有这种疯狂背后的逻辑。

+1

在您的示例中,“BaseListContainerComponent”与“BaseListComponent”不同。您的示例在[TypeScript Playground](https://www.typescriptlang.org/play/)中适用于我。 – Raven

+0

对不起,我简化了名字,但忘了在错误信息中也这么做。这真是奇怪,它不能在角度环境中工作,但它在操场上...... – Tom

+0

在您的错误消息中,您试图将“OR”类型(“{} | {}”)分配给数组('{...} []') – Raven

采用了棱角分明的Type界面解决方案。 Type可以找到更好的解释here。步骤来解决:

  1. 进口Type像这样:import { Type } from "@angular/core";

  2. 更换typeof BaseListComponentType<BaseListComponent>


对于人来这里谁不使用的角度,this thread可能会有所帮助。

我可能是错的,但是,这不是component: typeof BaseListComponent宣布componentType

应该不是只是component: BaseListComponent

+0

感谢您的回答:它会导致错误:'Type'({title:string; component:typeof QuestionsContainerComponent;} | {title:string; component:... '不能分配给类型'{title:string; component:BaseListContainerComponent;} []'。' – Tom