我在弄清楚接口(interface)中定义构造函数的工作方式时遇到了一些问题。我可能完全误解了一些东西。但是我已经搜索了很长时间的答案,但找不到与此相关的任何内容。
如何在 TypeScript 类中实现以下接口(interface):
interface MyInterface {
new ( ... ) : MyInterface;
}
Anders Hejlsberg 在 video 中创建了一个包含类似内容的界面(大约 14 分钟)。但对于我来说,我无法在类里面实现这一点。
我可能误解了什么,我没有得到什么?
编辑:
澄清一下。对于“新的(...)”,我的意思是“任何东西”。我的问题是我什至无法获得此工作的最基本版本:
interface MyInterface {
new () : MyInterface;
}
class test implements MyInterface {
constructor () { }
}
这不是为我编译我在尝试编译它时得到“Class 'test' declares interface 'MyInterface' but does not implement it: Type 'MyInterface' requires a construct signature, but Type 'test' lacks one”。
编辑:
所以在研究了这个之后,给出了反馈。
interface MyInterface {
new () : MyInterface;
}
class test implements MyInterface {
constructor () => test { return this; }
}
不是有效的 TypeScript,这不能解决问题。您不能定义构造函数的返回类型。它将返回“测试”。下列人员的签名: 类测试{ 构造函数(){} } 似乎是“new () => test”(通过将鼠标悬停在在线编辑器中的“类”上并粘贴该代码获得)。这就是我们想要的,也是我认为的。
任何人都可以提供一个实际编译的例子或类似的东西吗?
编辑(再次......):
所以我可能想出了一个想法,为什么可以在接口(interface)中定义它,但不能在 TypeScript 类中实现。以下工作:
var MyClass = (function () {
function MyClass() { }
return MyClass;
})();
interface MyInterface {
new () : MyInterface;
}
var testFunction = (foo: MyInterface) : void => { }
var bar = new MyClass();
testFunction(bar);
那么这是否只是 TypeScript 的一个功能,可以让您连接 javascript?或者是否可以在 TypeScript 中实现它而不必使用 javascript 实现类?
最佳答案
接口(interface)中的构造签名不能在类中实现;它们仅用于定义定义"new"功能的现有 JS API。这是一个涉及接口(interface) new
签名的示例,它确实有效:
interface ComesFromString {
name: string;
}
interface StringConstructable {
new(n: string): ComesFromString;
}
class MadeFromString implements ComesFromString {
constructor (public name: string) {
console.log('ctor invoked');
}
}
function makeObj(n: StringConstructable) {
return new n('hello!');
}
console.log(makeObj(MadeFromString).name);
这为您可以调用 makeObj
的内容创建了一个实际约束:
class Other implements ComesFromString {
constructor (public name: string, count: number) {
}
}
makeObj(Other); // Error! Other's constructor doesn't match StringConstructable
关于typescript - 带有构造签名的接口(interface)如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13407036/