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

时间:2021-03-27 21:38:04

标签: typescript

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

interface Entity {
  save: () => ClassThatImplementsEntity
}

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

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

1 个答案:

答案 0 :(得分:2)

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

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

看起来这是你需要的东西