【问题标题】:How to specialize template type of a generic class in typescript?如何在打字稿中专门化泛型类的模板类型?
【发布时间】:2018-08-18 13:36:33
【问题描述】:

是否可以在typescript的泛型函数中特化泛型类的模板类型?

假设我有一个通用接口和一个以接口构造函数为参数的函数:

interface IA<T> {
    func(arg: T)
}

function g<T, IAType extends IA<T>>(
    constructor: { new(): IAType }
): (arg: T) => IAType {
    const ins = new constructor();
    return arg => {
        ins.func(arg);
        return ins;
    }
}

然后我提供类实现IA&lt;T&gt;,即

class A implements IA<{ key: string }> {
    func(arg: { key: string }) {
        console.log(arg.key);
    }
}

const t = g(A); // type of t is (arg: {}) => A

如何编写函数 g 或类 A 以便函数 g 由于传入参数而可以专门化正确的模板类型?我想最终的t 的类型为(arg: {key: string}) =&gt; A

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    此类型为constructor 参数为g

     constructor: { new(): IAType }
    

    并没有真正强加一个约束,即IAType 中的func() 必须将T 作为其参数类型。唯一的约束是IAType extends IA&lt;T&gt;,这意味着IAType 中的func 可以有任何类型,只要它与func(arg: T) 兼容。推理算法可能从 {} 的最小类型开始,验证 func(arg: {}) 与 func(arg: T) 兼容,然后就停止了。

    对constructor 类型更严格会有所帮助:

    interface IA<T> {
        func(arg: T): void
    }
    
    function g<T, IAType extends IA<T>>(
        constructor: { new(): IA<T> & IAType }
    ): (arg: T) => IAType {
        const ins = new constructor();
        return arg => {
            ins.func(arg);
            return ins;
        }
    }
    
    class A implements IA<{ key: string }> {
        func(arg: { key: string }) {
            console.log(arg.key);
        }
    }
    
    const t = g(A); // type of t is (arg: { key: string; }) => A
    

    IA&lt;T&gt; &amp; IAType 都是必需的。如果您只有IA&lt;T&gt;,则将根据需要推断arg 类型,但返回类型将只有IA&lt;T&gt;,而不是A。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多