我一直在使用TypeScript中的构造签名接口,当下面的键入检查失败时,我变得有点困惑:
class Foo {
constructor () {
}
}
interface Bar {
new(): Bar;
}
function Baz(C : Bar) {
return new C()
}
var o = Baz(Foo);
Run Code Online (Sandbox Code Playgroud)
类型错误是:
提供的参数与调用目标的任何签名都不匹配:构造类型'new()=> Foo'和'Bar'的签名不兼容:类型'Bar'需要构造签名,但Type'Foo'缺少一个(C:Bar) )=>吧
Foo的构造函数的类型是()=> Foo,这就是我认为Bar所说的.我在这里错过了什么吗?
这是代码的更新版本,带有微妙的变化.
我们Bar使用我们期望存在的任何函数和变量来定义接口.
接下来,我们使用Bar接口扩展NewableBar接口.这只是定义了一个返回一个的构造函数Bar.
因为Fooimplements Bar和具有构造函数并且Baz需要a NewableBar,所以检查所有内容.
这比一些更冗长any- 但给你你想要的检查.
interface Bar {
}
interface NewableBar extends Bar {
new();
}
class Foo implements Bar {
constructor () {
}
}
function Baz(C : NewableBar) {
return new C()
}
var o = Baz(Foo);
Run Code Online (Sandbox Code Playgroud)
问题(至少从 TypeScript 编译器的角度来看)是Barsnew方法的签名。如果将 的定义替换Bar为以下内容,
interface Bar {
new (): any;
}
Run Code Online (Sandbox Code Playgroud)
有用。您不妨使用new (): Foo,就像Bar返回值不起作用一样。
| 归档时间: |
|
| 查看次数: |
9319 次 |
| 最近记录: |