问题描述
如何编写一个实现此 TypeScript 接口的类(并使 TypeScript 编译器满意):
How do I write a class that implements this TypeScript interface (and keeps the TypeScript compiler happy):
interface MyInterface {
(): string;
text2(content: string);
}
我看到了这个相关的答案:如何让一个类在打字稿?
I saw this related answer:How to make a class implement a call signature in Typescript?
但这仅在接口只有裸函数签名时才有效.如果您有其他成员(例如函数 text2)要实现,则它不起作用.
But that only works if the interface only has the bare function signature. It doesn't work if you have additional members (such as function text2) to be implemented.
推荐答案
一个类无法实现 typescript 接口中可用的所有内容.两个主要示例是可调用签名和索引操作,例如: 实现可索引的接口
A class cannot implement everything that is available in a typescript interface. Two prime examples are callable signatures and index operations e.g. : Implement an indexible interface
原因是接口主要用于描述 JavaScript 对象可以执行的任何操作.因此它需要非常健壮.然而,TypeScript 类旨在以更面向对象的传统/易于理解/易于键入的方式专门表示原型继承.
The reason is that an interface is primarily designed to describe anything that JavaScript objects can do. Therefore it needs to be really robust. A TypeScript class however is designed to represent specifically the prototype inheritance in a more OO conventional / easy to understand / easy to type way.
您仍然可以创建一个遵循该接口的对象:
You can still create an object that follows that interface:
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;
}
);
这篇关于使用裸函数签名和其他字段实现 TypeScript 接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!