在typescript中定义typeof抽象类

时间:2017-06-15 10:47:30

标签: angular class typescript types abstract-class

如何使typeof BaseListComponent低于可分配?

以下代码会引发以下错误:

  

类型“({ title: string; component: typeof QuestionsListComponent; } | { title: string; component: ...'不能分配给'{ 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这是一个角度应用程序的简化摘录,所以这种疯狂背后有逻辑。

2 个答案:

答案 0 :(得分:6)

使用angular的Type接口是解决方案。可以找到Type的更好解释here。要解决的步骤:

  1. 导入Type,如下所示:import { Type } from "@angular/core";

  2. typeof BaseListComponent替换为Type<BaseListComponent>

  3. 对于那些没有使用角度的人来说,this thread可能会有帮助。

答案 1 :(得分:0)

我可能错了,但component: typeof BaseListComponent声明component类型为Type

不应该只是component: BaseListComponent