TypeScript:从接口方法返回类的实例

ran*_*bey 4 typescript

如何将接口方法的返回类型指定为在 TypeScript 中实现该接口的类的实例?例如:

interface Entity {
  save: () => ClassThatImplementsEntity
}
Run Code Online (Sandbox Code Playgroud)

这样实现Entity接口的类将有一个返回该类实例的 save 方法

class User implements Entity {
  save() {
    // some logic
    return this;
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 6

通常你的接口不应该知道实现,但是如果save()应该准确返回类的类型,你可以使用

interface Entity {
  save: () => this
}

class E1 implements Entity {
    save() {
        return this
    }
}

class E2 extends E1 {

}
const e1 = new E1()
const e2 = new E2()
const x1 = e1.save() // type of x1 is E1
const x2 = e2.save() // type of x is E2
Run Code Online (Sandbox Code Playgroud)

看起来这是你需要的东西