如何将接口(interface)方法的返回类型指定为在 TypeScript 中实现接口(interface)的类的实例?例如:
interface Entity {
save: () => ClassThatImplementsEntity
}
这样一个实现 Entity
的类接口(interface)将有一个保存方法,该方法返回该类的实例class User implements Entity {
save() {
// some logic
return this;
}
}
最佳答案
通常你的接口(interface)不应该知道实现,但是如果 保存()应该准确返回您可以使用的类的类型 这个
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
看起来这是你需要的东西
关于TypeScript:从接口(interface)方法返回类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66836372/