Typescript - 是否可以让接口定义带有泛型的构造函数?

Bri*_*ian 2 generics typescript

我基本上是在尝试做这样的事情:

interface gen1<T> {
    constructor(param: T);
}
interface gen2<T> {
    constructor(param: gen1<any>);
}
class genImpl implements gen2<any> {
    constructor(param: gen1<any>) {

    }
}
Run Code Online (Sandbox Code Playgroud)

但得到错误:

Class 'genImpl' incorrectly implements interface 'gen2<any>'.
  Types of property 'constructor' are incompatible.
    Type 'Function' is not assignable to type '(param: gen1<any>) => any'.
      Type 'Function' provides no match for the signature '(param: gen1<any>): any'.
Run Code Online (Sandbox Code Playgroud)

Sar*_*ana 8

接口中的构造函数签名不能在类中实现。这是设计使然。从文档

在使用类和接口时,记住类有两种类型会有所帮助:静态端的类型和实例端的类型。您可能会注意到,如果您创建一个带有构造签名的接口并尝试创建一个实现此接口的类,则会出现错误:

interface ClockConstructor {
    new (hour: number, minute: number);
}

class Clock implements ClockConstructor {
    currentTime: Date;
    constructor(h: number, m: number) { }
}
Run Code Online (Sandbox Code Playgroud)

这是因为当一个类实现一个接口时,只检查该类的实例端。由于构造函数位于静态端,因此不包括在此检查中。

相反,您需要直接使用类的静态端。在这个例子中,我们定义了两个接口,用于构造函数的 ClockConstructor 和用于实例方法的 ClockInterface。然后为了方便起见,我们定义了一个构造函数 createClock 来创建传递给它的类型的实例。

interface ClockConstructor {
    new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
    tick();
}

function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
    return new ctor(hour, minute);
}

class DigitalClock implements ClockInterface {
    constructor(h: number, m: number) { }
    tick() {
        console.log("beep beep");
    }
}
class AnalogClock implements ClockInterface {
    constructor(h: number, m: number) { }
    tick() {
        console.log("tick tock");
    }
}

let digital = createClock(DigitalClock, 12, 17); let analog =
createClock(AnalogClock, 7, 32); 
Run Code Online (Sandbox Code Playgroud)

因为 createClock 的第一个参数是 ClockConstructor 类型,所以在 createClock(AnalogClock, 7, 32) 中,它会检查 AnalogClock 是否具有正确的构造函数签名。

相关讨论:https : //github.com/Microsoft/TypeScript/issues/8917