我目前正在开发一个 TypeScript API,它需要一些绑定到对象原型 (Object.prototype) 的附加功能。
考虑以下代码:
class Foo {
}
interface Object {
GetFoo(): Foo;
GetFooAsString(): string;
}
//This is problematic...
Object.prototype.GetFoo = function() {
return new Foo();
// Note, this line is just for testing...I don't want my function to just return a blank instance of Foo!
}
//This is ok.
Object.prototype.GetFooAsString = function () {
return this.GetFoo().toString();
}
您可能想直接在Playground上尝试一下。
如您所见,我有一个名为Foo
(不是我将使用的实际对象名称)的类。我还扩展了Object
界面以包含两个新功能。最后,我实现了针对 的函数prototype
(这些在纯 JavaScript 中工作,只是 TypeScript 抱怨)。
在我注释的地方“ //这是有问题的...... ” TypeScript 用红色波浪线突出显示,并显示以下错误:
Cannot convert '() => Foo' to '{ (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; }': Call signatures of types '() => Foo' and '{ (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; }' are incompatible
() => Foo
要么这只是一个 TypeScript 错误(我知道它仍处于开发阶段,所以很多错误需要解决,我已经在 CodePlex 上说明了其中的一些),或者我遗漏了一些东西。
为什么我会遇到这个问题?
如果不是 TypeScript 错误,我该如何解决?