我从正在使用的库中收到以下界面:

export interface LatLng {
  constructor(lat: number, lng: number): void;
  lat(): number;
  lng(): number;
}

如何创建此类的实现?(我需要一个测试模拟)一个外观自然的实现,其构造函数定义如下:

export class LatLngImpl implements LatLng {
  constructor(private _lat: number, private _lng: number) {  }

不编译:

Class 'LatLngImpl' incorrectly implements interface 'LatLng'. Types of property 'constructor' are incompatible. Type 'Function' is not assignable to type '(lat: number, lng: number) => >void'. Type 'Function' provides no match for the signature '(lat: number, lng: >number): void'

我在typescript中读到了constructor接口,但我认为它在这里不适用.

Edit:

我不理解的是界面中的constructor()条声明.具有构造函数签名的接口使用new ()语法.

推荐答案

这个图书馆从哪里来?不管是谁写的,都应该受到严厉的批评.要么是一个错误(在这种情况下,他们从来没有测试过它),要么是故意的,但很糟糕:使用not-quite-reserved wordconstructor作为实例方法的标识符只是自找麻烦.

EDIT 2019-04-25:麻烦不仅仅是"这是个坏主意";它实际上看起来像是JavaScript本机支持类字段it is going to be an error to have a class with a property named "constructor".TypeScript将在3.5+版本中更改以反映这一点,因此下面的实现将停止工作.有关更多信息,请参阅最近发布的GitHub第Microsoft/TypeScript#3constructor0期.在TS3之后.5看起来不可能有一个实例constructor属性不是实际构造函数本身的类.

要么库作者打算引用你用new调用的一个真正的构造函数,在这种情况下,他们应该做一些类似@Series0ne's suggestion的事情;or作者真的想使用实例方法来初始化对象,在这种情况下,他们应该帮每个人的忙,使用更传统的方法名称,如init().

在任何一种情况下,都不应该有人接受你得到的接口,当然也不应该有人实现它.

让我们来实现它:

export class LatLngImpl implements LatLng {
  private _lat: number;
  private _lng: number;
  lat() {
    return this._lat;
  }
  lng() {
    return this._lng;
  }
  // here's the important part, but see Microsoft/TypeScript#31020
  "constructor"(lat: number, lng: number) { 
    this._lat = lat;
    this._lng = lng;
  }
}

诀窍是使用字符串文字"constructor"而不是简单的单词constructor.从TypeScript spec人中:

字符串文字可用于提供无效标识符的属性名称

通过使用字符串文字,我们能够将其声明为一个实例方法,而不是调用new时调用的静态类构造函数方法,并且它可以很好地编译.

现在我们可以使用它,如果我们敢:

const latLng = new LatLngImpl();
latLng.constructor(47.6391132, -122.1284311); // ? Why not init()?
console.log("Latitude: " + latLng.lat() + ", Longitude: " + latLng.lng());

哎呀,我们不该这么做.

EDIT AGAIN 2019-04-25上面引用的字符串实现将从TypeScript 3.5开始,正确答案是"你不能这么做"和"使用真正的构造函数".

希望有帮助;祝你好运

Typescript相关问答推荐

如何准确确定此特定场景中的类型?

如何将http上下文附加到angular中翻译模块发送的请求

泛型函数类型验证

当使用`type B = A`时,B的类型显示为A.为什么当`type B = A时显示为`any `|用A代替?

如何缩小变量访问的对象属性范围?

如何按不能保证的功能过滤按键?

角效用函数的类型推断

TS如何不立即将表达式转换为完全不可变?

为什么我的查询钩子返回的结果与浏览器的网络选项卡中看到的结果不同?

刷新页面时,TypeScrip Redux丢失状态

是否有可能避免此泛型函数体中的类型断言?

Typescript 中相同类型的不同结果

必需的输入()参数仍然发出&没有初始值设定项&q;错误

Typescript .根据枚举输入参数返回不同的对象类型

如何使函数参数数组不相交?

为什么数字是`{[key:string]:UNKNOWN;}`的有效密钥?

导航链接不触发自定义挂钩

Typescript循环函数引用

Typescript泛型-键入对象时保持推理

TypeScript是否不知道其他函数内部的类型判断?