2014-02-06 48 views
1

我有一個實現接口的類。兩者都定義了一個方法,它接受一個泛型並輸出一個與泛型相同類型的數組。我收到了關於類和接口之間不一致的奇怪錯誤,我不知道如何解決它。下面是一些示例代碼:用泛型重載方法時出現奇怪的錯誤

class Random implements IRandom { 
    generateArray<T>(method: string): Array<T>; 
    generateArray<T>(Constructor: new() => T): Array<T>; 
    generateArray(method: any) { 
     return new Array<any>(); 
    } 
} 

interface IRandom { 
    generateArray<T>(method: string): Array<T>; 
    generateArray<T>(Constructor: new() => T): Array<T>; 
} 

這裏是上面的代碼中的錯誤片段:

Class Random declares interface IRandom but does not implement it: 
    Types of property 'generateArray' of types 'Random' and 'IRandom' are incompatible: 
     Call signatures of types '{ <T>(method: string): T[]; <T>(Constructor: new() => T): T[]; }' and '{ <T>(method: string): T[]; <T>(Constructor: new() => T): T[]; }' are incompatible: 
      Types of property 'concat' of types '{}[]' and 'T[]' are incompatible: 
       Call signatures of types '{ <U extends T[]>(...items: U[]): {}[]; (...items: {}[]): {}[]; }' and '{ <U extends T[]>(...items: U[]): T[]; (...items: T[]): T[]; }' are incompatible: 
        Types of property 'pop' of types '{}[]' and 'T[]' are incompatible: 
         Call signatures of types '() => {}' and '() => T' are incompatible. 

有沒有人遇到這個錯誤?有沒有辦法解決它?

+0

的可能重複[通用接口聲明未正常工作,是打字稿0.9.5(HTTP://計算器。 com/questions/20437528/generic-interface-declaration-not-working-as-is-on-typescript-0-9-5) – WiredPrairie

+0

你的代碼爲我編譯。你有安裝最新版本的打字機嗎? – Kyle

+0

我正在使用VS 2013的插件,運行v0.9.5。有更新的版本嗎?也許我應該重新安裝。 – wjohnsto

回答

1

你偶然發現了一個錯誤 - 但它has been fixed(這樣會推出下一個版本)...

在此期間,有兩種解決方法可用...

使界面和類通用(而不是方法)。

interface IRandom<T> { 
    generateArray(method: string): T[]; 
    generateArray(Constructor: new() => T): T[]; 
} 

class Random<T> implements IRandom<T> { 
    generateArray(method: string): T[]; 
    generateArray(Constructor: new() => T): T[]; 
    generateArray(method: any) { 
     return new Array<any>(); 
    } 
} 

或者使用類(作爲臨時措施)定義的接口。這將允許您在修復bug時通過刪除extends Random來修改表格,並重新添加界面主體並放回implements IRandom

interface IRandom extends Random { 

} 

class Random { 
    generateArray<T>(method: string): Array<T>; 
    generateArray<T>(Constructor: new() => T): Array<T>; 
    generateArray(method: any) { 
     return new Array<any>(); 
    } 
} 

所有調用代碼將不知道的欺騙:

function paramIsInterface(param: IRandom) { 
    // Stuff 
} 

var r = new Random(); 

paramIsInterface(r); // Accepts Random is an IRandom... 
+0

謝謝!我想我暫時不得不選擇選項2。 – wjohnsto