Typescript 类无法使用构造函数实现简单接口?

Gre*_*egg 0 typescript

我很难理解这个实现的问题出在哪里。我创建了一个简单的测试类,它使用构造函数实现了一个非常简单的接口,而 Typescript 编译器表示存在问题。

BaseEntity.ts:

export interface IBaseEntity {
  id: string
  new(_id?: string, _data?: any)
}
Run Code Online (Sandbox Code Playgroud)

测试.ts:

class Test implements IBaseEntity {
  id: string
  constructor(_id?: string, _data?: any) {
    this.id = 'MOCK_ID'
  }
}
Run Code Online (Sandbox Code Playgroud)

错误:

Class 'Test' incorrectly implements interface 'IBaseEntity'.
  Type 'Test' provides no match for the signature 'new (_id?: string | undefined, _data?: any): any'.
Run Code Online (Sandbox Code Playgroud)

我希望有人能很快指出问题出在哪里,因为在我看来这是正确的。预先感谢大家。

Tit*_*mir 5

这是对什么的误解implementsimplements确保类的实例类型满足接口指定的契约。类的构造函数不是实例类型的一部分,它是类类型的一部分(类的静态部分)。

您需要将接口的静态部分与实例部分分开:

export interface IBaseEntity {
  id: string

}

export interface IBaseEntityClass {
    new(_id?: string, _data?: any): IBaseEntity
}


class Test implements IBaseEntity {
  id: string
  constructor(_id?: string, _data?: any) {
    this.id = 'MOCK_ID'
  }
}
let baseEntityClass: IBaseEntityClass = Test; // The class test fulfills the contract of IBaseEntityClass

new baseEntityClass("", {}) // constructing through IBaseEntityClass interface

Run Code Online (Sandbox Code Playgroud)

游乐场链接

目前无法指定类类型需要实现特定接口,但let baseEntityClass: IBaseEntityClass = Test如果Test没有正确的构造函数,您将在赋值时遇到错误。