繁体   English   中英

如何在打字稿中专门化泛型类的模板类型?

[英]How to specialize template type of a generic class in typescript?

是否可以在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<T> ,即

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}) => A

此类型为g constructor参数

 constructor: { new(): IAType }

并没有真正施加约束, IAType中的func()必须以T作为其参数类型。 唯一的约束是IAType extends IA<T> ,这意味着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<T> & IAType都是必需的。 如果只有IA<T> ,则将根据需要推断arg类型,但是返回类型将仅为IA<T> ,而不是A

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM