2014-02-06 46 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