使用裸函数签名和其他字段实现TypeScript接口 [英] Implementing TypeScript interface with bare function signature plus other fields

查看:436
本文介绍了使用裸函数签名和其他字段实现TypeScript接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写实现此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);
}

我看到了这个相关答案:
如何让类在Typescript中实现调用签名?

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.

推荐答案

一个类无法实现一切在打字稿界面中可用。两个主要的例子是可调用的签名和索引操作,例如:实施可索引的界面

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类旨在以更为OO的常规/易于理解/易于类型的方式专门表示原型继承。

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接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆