使用一般类型接口一般类型 class

Generically type a class using a generically typed interface

这是一个纯粹的 Typescript/Generics 问题。我的问题来源于Angular/CDK (portal.d.ts):

/** Interface that can be used to generically type a class. */
export interface ComponentType<T> {
    new (...args: any[]): T;
}

我正在努力解决这个问题,但到目前为止运气不佳。问题可以从我写的测试代码看明白这个:

export interface ComponentType<T> {
    new (...args: any[]): T;
}

interface Bar<T> {
    getData: () => T
}

class MyBooleanComponent implements Bar<boolean> {
    getData(): boolean { return true; }
}


class MyGenericWrapper {
    init<T>(comp: ComponentType<T>): T {
        return new comp();
    }
}

const wrapper = new MyGenericWrapper();
const instance = wrapper.init<boolean>(MyBooleanComponent);

(instance as Bar).getData();

CODE

可以看出这段代码存在一些问题。

首先,MyBooleanComponent,不能分配给ComponentType<boolean>。我不清楚如何分辨 MyBooleanComponent` returns 布尔值?

其次,如果我转换 (instance as Bar).getData(); 打字稿编译器对 Bar 不满意,它想要 (instance as Bar<boolean>).getData(); 但我会根据我 initialized/setup 整个事情的方式进行期望应该可以导出 boolean 对吧?

如果我做错了什么或者试图做不可能的事情,我就不会使用。任何帮助将不胜感激!

我认为混淆是 MyGenericWrapper 中的类型 T 与接口 Bar 中的类型 T 不同。您已通过 MyBooleanComponenet:

将接口 Bar 的通用类型设置为布尔值
class MyBooleanComponent implements Bar<boolean> {
    getData(): boolean { return true; }
}

其中 MyGenericWrapper 的通用类型设置为 MyBooleanComponent

const wrapper = new MyGenericWrapper();
const instance = wrapper.init<MyBooleanComponent>(MyBooleanComponent);
instance.getData();

Working example.