2017-04-24 195 views
0

基本上,我试图做这样的事情:Typescript - 是否有可能使用泛型定义构造函数的接口?

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

    } 
} 

,但得到的错误:

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'. 

回答

2

接口中的构造函数签名在类中无法实现。这是设计。从documentation

When working with classes and interfaces, it helps to keep in mind that a class has two types: the type of the static side and the type of the instance side. You may notice that if you create an interface with a construct signature and try to create a class that implements this interface you get an error:

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

class Clock implements ClockConstructor { 
    currentTime: Date; 
    constructor(h: number, m: number) { } 
} 

This is because when a class implements an interface, only the instance side of the class is checked. Since the constructor sits in the static side, it is not included in this check.

Instead, you would need to work with the static side of the class directly. In this example, we define two interfaces, ClockConstructor for the constructor and ClockInterface for the instance methods. Then for convenience we define a constructor function createClock that creates instances of the type that is passed to it.

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); 

Because createClock’s first parameter is of type ClockConstructor, in createClock(AnalogClock, 7, 32), it checks that AnalogClock has the correct constructor signature.

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

+0

这是...不幸...,但谢谢你的回应! – Brian

0

Is it possible to have generics in constructor?

but getting error

原因是gen<T>是不一样的as T

修复
interface gen<T> { 
    constructor(param: T); 
} 

class genImpl implements gen<any> { 
    constructor(param: any) { 

    } 
} 

即使用any其中曾被使用T。 (您犯了将T同时设置为gen<any>any的错误)

+0

woops,坏榜样,1秒,让我解决它 – Brian

+0

赶到 – Brian

+0

您的意思是写'声明class'或问题,它现在已经更新'interface','new()'和'const'的组合?这是行不通的,因为构造函数基本上是静态的。 –

相关问题