简体   繁体   English

Angular / Typescript:编写从基类派生的工厂返回类型

[英]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.

相关问题 Angular:如何将参数从派生组件类传递给基类 - Angular: How to pass arguments from derived component class to base class 如何避免在TypeScript,Angular2的派生类中重复基类构造函数参数? - How to avoid repeating base class constructor parameters in derived class in TypeScript, Angular2? 无法从派生类访问/获取抽象(基)类属性的值 - TypeScript - Unable to access/get value of abstract (base) class properties from derived class - TypeScript Angular2 - 来自TypeScript基础抽象类的@ViewChild - Angular2 — @ViewChild from TypeScript base abstract class 从函数的派生类访问基本成员 - Accessing base member from derived class in function 如何获取基类(Angular2 +)中的派生类名称? - How to get the derived class name in the base class (Angular2+)? 将派生类属性传递给 Angular 中的基类构造函数时出错 - Error on passing derived class properties to the base class constructor in Angular Angular - 如何将参数传递给 TypeScript 基类 - Angular - How to pass parameters to TypeScript base Class angular2 / typescript类继承与泛型类型 - angular2 / typescript class inheritance with generic types 如果私有变量已初始化(Angular 2,TypeScript),则在派生的 class 中未定义注入服务 - Injected service is undefined in derived class if private variable is initialized (Angular 2, TypeScript)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM