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

TypeScript:从接口方法返回类的实例,typescript,Typescript,如何将接口方法的返回类型指定为TypeScript中实现接口的类的实例?例如: interface Entity { save: () => ClassThatImplementsEntity } 这样,实现实体接口的类将有一个save方法返回该类的实例 class User implements Entity { save() { // some logic return this; } } 通常,您的接口不应该知道实现,但是如果save()应该返回您可以

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

interface Entity {
  save: () => ClassThatImplementsEntity
}
这样,实现<代码>实体接口的类将有一个save方法返回该类的实例

class User implements Entity {
  save() {
    // some logic
    return this;
  }
}

通常,您的接口不应该知道实现,但是如果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

看起来这是您需要的

接口通常不应该知道实现。你能解释一下为什么你需要这样的东西吗?@dm.shpak我需要它来让方法可以链接