我在解决界面中定义构造函数的工作方式时遇到了一些麻烦.我可能完全误解了一些事情.但是我已经寻找了很长一段时间的答案,我找不到与此相关的任何内容.
如何在TypeScript类中实现以下接口:
interface MyInterface {
new ( ... ) : MyInterface;
}
Run Code Online (Sandbox Code Playgroud)
Anders Hejlsberg在此视频中创建了一个包含类似内容的界面(大约14分钟).但对于我的生活,我无法在课堂上实现这一点.
我可能误解了一些事情,我没有得到什么?
编辑:
澄清.用"new(...)"我的意思是"任何东西".我的问题是我无法得到这个工作的最基本版本:
interface MyInterface {
new () : MyInterface;
}
class test implements MyInterface {
constructor () { }
}
Run Code Online (Sandbox Code Playgroud)
这不是为我编译我得到"类'测试'声明接口'MyInterface'但没有实现它:类型'MyInterface'需要一个构造签名,但类型'test'在尝试编译它时缺少一个.
编辑:
因此,在研究了这一点后,给出了反馈意见.
interface MyInterface {
new () : MyInterface;
}
class test implements MyInterface {
constructor () => test { return this; }
}
Run Code Online (Sandbox Code Playgroud)
是无效的TypeScript,这不能解决问题.您无法定义构造函数的返回类型.它将返回"测试".下面的签名:class test {constructor(){}}似乎是"new()=> test"(通过将"代码"粘贴在在线编辑器中,将鼠标悬停在"class"上获得).这就是我们想要的和我认为的.
任何人都可以在实际编译时提供此类或类似的示例吗?
编辑(再次......):
所以我可能想出了为什么可以在接口中定义它但不能在TypeScript类中实现的想法.以下工作:
var MyClass = (function () {
function MyClass() { }
return …Run Code Online (Sandbox Code Playgroud)