[英]Angular/Typescript: write a factory returning types derived from base class
I'm trying to write a factory method that returns classes, like this: 我正在尝试编写一个返回类的工厂方法,如下所示:
getWidget<T extends WidgetBase>(componentName: string): Type<T> {
switch (componentName) {
default:
throw new Error(`Widget ${componentName} is not registered in the system`);
case "Widget2":
return Widget2Component;
}
}
where Widget2Component is a classe defined in another file (Angular component) which derives from WidgetBase, and abstract class, and Type<> is an Angular interface defined like this: 其中Widget2Component是在另一个文件(Angular组件)中定义的类,该文件派生自WidgetBase和抽象类,Type <>是Angular接口,定义如下:
interface Type<T> extends Function {
new (...args: any[]): T
}
The compiler complains: 编译器抱怨:
Type 'typeof Widget2Component' is not assignable to type 'Type<T>'
. 类型'typeof Widget2Component'不可分配给类型'Type<T>'
。 Type 'Widget2Component' is not assignable to type 'T'
. 类型'Widget2Component'不可分配给类型'T'
。
but I don't get why... Widget2Component extends WidgetBase! 但是我不明白为什么... Widget2Component扩展了WidgetBase!
Titian is right in what he said in the comments... So I modified my method to this: 提香(Titian)在他的评论中说的是正确的...因此我将方法修改为:
getWidget(componentName: string): Type<WidgetBase> {
switch (componentName) {
default:
throw new Error(`Widget ${componentName} is not registered in the system`);
case "Widget1":
return Widget1Component;
case "Widget2":
return Widget2Component;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.