如何编写一个实现此 TypeScript 接口的类(并使 TypeScript 编译器满意):
interface MyInterface {
(): string;
text2(content: string);
}
我看到了这个相关的答案:如何让一个类在 Typescript 中实现调用签名? https://stackoverflow.com/questions/12769636/how-to-make-a-class-implement-a-call-signature-in-typescript
但这仅在接口仅具有裸函数签名时才有效。如果您有其他要实现的成员(例如函数text2),则它不起作用。
类无法实现打字稿接口中可用的所有内容。两个主要的例子是可调用签名和索引操作,例如:实现可索引接口 https://stackoverflow.com/questions/16248812/implement-an-indexible-interface
原因是接口主要是为了描述 JavaScript 对象可以执行的任何操作而设计的。因此它必须非常坚固。然而,TypeScript 类被设计为以更面向对象的传统/易于理解/易于键入的方式专门表示原型继承。
您仍然可以创建遵循该接口的对象:
interface MyInterface {
(): string;
text2(content: string);
}
var MyType = ((): MyInterface=>{
var x:any = function():string { // Notice the any
return "Some string"; // Dummy implementation
}
x.text2 = function(content:string){
console.log(content); // Dummy implementation
}
return x;
}
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)