使用通用类型的接口通用类型的类

时间:2019-11-22 10:14:38

标签: typescript generics 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

enter image description here

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

首先,MyBooleanComponent,不可分配给ComponentType<boolean>。我不清楚如何分辨MyBooleanComponent返回布尔值?

第二,如果我强制转换(instance as Bar).getData();的打字稿编译器对Bar不满意,它希望(instance as Bar<boolean>).getData();,但我希望基于我初始化/设置整个过程的方式,这应该是可能的推导出boolean对吗?

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

1 个答案:

答案 0 :(得分:1)

我认为混淆之处在于T中的类型MyGenericWrapper与接口T中的类型Bar不同。您已将接口Bar的通用类型设置为MyBooleanComponenet的布尔值:

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.