2013-07-25 164 views
12

我試圖發現將多個接口合併爲一個抽象類的模式。目前我可以通過「實現」組合多個接口,但接口無法聲明構造函數。當我必須介紹構造函數時,我不得不使用抽象類。當我使用抽象類時,我必須重新聲明整個複合接口!當然,我錯過了什麼?Typescript多重繼承解決方法?

interface ILayerInfo { 
    a: string; 
} 

interface ILayerStatic { 
    b(): string; 
} 

class Layer implements ILayerInfo, ILayerStatic { 
    constructor(info: ILayerInfo); 
    a: string; 
    b(): string; 
} 

答:使用「新」:

interface Layer extends ILayerInfo, ILayerStatic { 
    new(info: ILayerInfo); 
} 

// usage: new Layer({ a: "" }); 

回答

21

聲明相同的接口實例成員構造並沒有真正多大意義 - 如果你打算在傳遞動態類型以在構造函數中使用,它是將被限制的類的靜態一面。你會想這樣做大概是這樣的:

interface Colorable { 
    colorize(c: string): void; 
} 

interface Countable { 
    count: number; 
} 

interface ColorCountable extends Colorable, Countable { 
} 

interface ColorCountableCreator { 
    new(info: {color: string; count: number}): ColorCountable; 
} 

class ColorCounted implements ColorCountable { 
    count: number; 
    colorize(s: string) { } 
    constructor(info: {color: string; count: number}) { 
     // ... 
    } 
} 

function makeThings(c: ColorCountableCreator) { 
    var results: ColorCountable[]; 
    for(var i = 0; i < 10; i++) { 
     results.push(new c({color: 'blue', count: i})); 
    } 
    return results; 
} 

var items = makeThings(ColorCounted); 
console.log(items[0].count); 

參見How does typescript interfaces with construct signatures work?

+0

這是我失蹤了界面上的「新」的關鍵字!我根本不想上課。隨着「新」,我可以堅持接口。 –