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

标签 typescript

如何将接口(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/

相关文章:

typescript - 如何在 typescript 中将对象数组转换为uri编码的查询字符串

typescript - Typescript是否允许将 “any”分配给其他所有类型?如何处理渔获(错误: any)?

ElementRef 上的 Angular2 getElementsByClassName

typescript - 类型错误 : Cannot read property 'Symbol(Symbol.iterator)' of undefined

javascript - 我如何在angular2中将x个月添加到当前日期

typescript - vue 类组件 : how to create and initialize reflective data

TypeScript:如何向内置类添加静态方法

angular - 如何使用 Observable 调用等待事件订阅者完成

json - Angular 2 Pipe - 按 JSON 键过滤

javascript - TypeScript 接口(interface)上的可选参数