【问题标题】:Typescript define generic constructor function打字稿定义通用构造函数
【发布时间】:2016-04-23 00:38:25
【问题描述】:

我正在尝试将 Typescript 与具有伪类的 JS 库以及提供继承的 extend() 函数一起使用。我被困在如何将不同的构造函数传递给新的“类”:

type A = (param1: string, param2: number);
type B = (param3: number, param4: number);

interface BaseClass {
    extend<Constructor>(): {
        new(); // How would I associate this function with type Constructor?
    }
}

var NewClass = BaseClass.extend<A>();
new NewClass('Hello world', 3); // type checked against type A

var SecondClass= BaseClass.extend<B>();
new SecondClass(4, 5); // type checked against type B

我试过这个:

interface BaseClass {
    extend<Constructor>(): {
        new(): Constructor;
    }
}

但这需要new NewClass() 返回类型 A。

我试过这个:

interface BaseClass {
    extend<Constructor>(): {
        new<Constructor>();
    }
}

但这不会输入检查new NewClass()

将函数与类型关联的正确语法是什么?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    new() 构造函数找到了解决方法。我更改了类型以包含 new 关键字本身:

    type A = {
        new(param1: string, param2: number);
    }
    
    type B = {
        new(param3: number, param4: number);
    }
    

    然后我可以像这样从extend() 调用返回构造函数:

    interface BaseClass {
        extend<Constructor>(): Constructor;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-22
      • 1970-01-01
      • 2022-01-15
      • 2022-01-23
      相关资源
      最近更新 更多