TypeScript:继承类中方法的自引用返回类型

Mer*_*ott 2 generics inheritance static self-reference typescript

免责声明:我发现很难在问题标题中概括问题,所以如果您有更好的建议,请在评论中告诉我。

让我们看一下以下简化的 TypeScript 类:

class Model {
  save():Model {
    // save the current instance and return it
  }
}
Run Code Online (Sandbox Code Playgroud)

该类Model有一个save()返回自身实例的方法: a Model

我们可以Model这样扩展:

class SomeModel extends Model {
  // inherits the save() method
}
Run Code Online (Sandbox Code Playgroud)

因此,SomeModel将继承save(),但它仍然返回 a Model,而不是 a SomeModel

有没有一种方法,也许使用泛型,将save()in的返回类型设置SomeModelSomeModel,而不必在继承类内部重新定义它?

Val*_*Val 6

我知道我迟到了,
@2019 我找到了一种使返回类型特定的方法:

class Model {
  save<T extends Model>(this: T): T {
    // save the current instance and return it
  }
}
Run Code Online (Sandbox Code Playgroud)

这样,无论 extendsModelModel它本身,在调用时都将被引用为返回类型。

对于 Typescript@3,这也有效:

class Model {
  save(): this {
    // save the current instance and return it
  }
}
Run Code Online (Sandbox Code Playgroud)