【问题标题】:Generically type a class using a generically typed interface使用泛型类型接口泛型类型类
【发布时间】:2019-11-22 10:14:38
【问题描述】:

这是一个纯粹的打字稿/泛型问题。我的问题来源于 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&lt;boolean&gt;。我不清楚如何判断 MyBooleanComponent` 返回布尔值?

其次,如果我投射(instance as Bar).getData();,打字稿编译器对Bar 不满意,它想要(instance as Bar&lt;boolean&gt;).getData();,但我希望根据我初始化/设置整个事情的方式,它应该可以推导出boolean 对?

如果我做错事或尝试做不可能的事,我不会使用。任何帮助将不胜感激!

【问题讨论】:

    标签: typescript generics typescript-generics


    【解决方案1】:

    我认为混淆是MyGenericWrapper 中的类型T 与接口Bar 中的T 类型不同。您已将接口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.

    【讨论】:

      猜你喜欢
      • 2019-07-21
      • 2016-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-12
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多