2014-10-30 116 views
1

通用擴展接口我想建立一個功能女巫採取任何對象,並返回該對象很少添加的屬性。是這樣的:在打字稿

//this code doesn't work 
     function addProperties<T>(object: T): IPropertiesToAdd<T> {/*implmentions code*/}; 

     interface IPropertiesToAdd<T> extend T{ 
      on(): void; 
      off(): void; 
     } 

//usage example 
var str = new String('Hello') 
addProperties(str) 
str.charAt(3) 
str.on() 

上面的代碼編譯打字稿返回錯誤的接口只能添加一個類或接口,我怎麼能在打字稿表達這一點。

回答

8

接口IPropertiesToAdd定義了用於擴展名爲T的接口的類型變量T。這不可能。無法使用變量名稱引用接口;它必須有一個固定的名字,例如Evnt:

interface Evnt<T> { 
    name: T; 
} 

interface IPropertiesToAdd<T> extends Evnt<T> { 
    on(): void; 
    off(): void; 
} 

我不確定你在試圖達到什麼樣的情況。我已經擴展的例子一點,所以它編譯:

function addProperties<T>(object: Evnt<T>): IPropertiesToAdd<T> { 
    /* minimum implementation to comply with interface*/ 
    var ext:any = {}; 
    ext.name = object.name 
    ext.on = function() {}; 
    ext.off = function() {}; 
    return ext; 
}; 

interface Evnt<T> { 
    name: T; 
} 

interface IPropertiesToAdd<T> extends Evnt<T> { 
    on(): void; 
    off(): void; 
} 

//usage example 
var str = {name: 'Hello'} 
var evnt = addProperties(str) 
evnt.charAt(3); // error because evnt is not of type 
       // `string` but `IPropertiesToAdd<string>` 
evnt.on() 
+0

感謝您的時間,在架構變化不大,你的答案真的幫助。 – user2692945 2014-10-30 14:26:30

3

您可以創建一個新的type alias,這將使你的對象繼承另一個對象類型的功能。我發現的代碼here該位。

type IPropertiesToAdd<T extends {}> = T & { // '{}' can be replaced with 'any' 
    on(): void 
    off(): void 
}; 

interface ISomething { 
    someValue: number 
} 

var extendedType: IPropertiesToAdd<ISomething> = { 
    on(): void { 
     console.log("switched on"); 
    }, 
    off(): void { 
     console.log("switched off"); 
    }, 
    someValue: 1234, 
}; 

我測試過了,看起來'T'可以是接口,類和數組類型。我無法使用工會類型。

這僅適用於匿名對象,它不能用於實際繼承的目的。

希望這會有所幫助。