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

时间:2015-12-04 18:50:51

标签: generics inheritance static typescript self-reference

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

让我们采用以下简化的TypeScript类:

class Model {
  save():Model {
    // save the current instance and return it
  }
}

Model类有一个save()方法,可以返回自己的实例:Model

我们可以这样扩展Model

class SomeModel extends Model {
  // inherits the save() method
}

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

是否有办法(可能使用泛型)将save()SomeModel的返回类型设置为SomeModel,而无需在继承类中重新定义它?

2 个答案:

答案 0 :(得分:1)

你很幸运。 Polymorphic this刚出现在TypeScript 1.7。升级到TypeScript 1.7,然后删除显式返回类型,它将完美地工作:

class Model {
    save() {
        return this;
    }
}

class SomeModel extends Model {
    otherMethod() {
    }
}

let someModel = new SomeModel().save();
// no compile error since someModel is typed as SomeModel in TS 1.7+
someModel.otherMethod();

答案 1 :(得分:0)

我知道我迟到了。
@ 2019我找到了一种使返回类型特定的方法,而不是return this

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

这样,无论扩展了Model还是Model本身,在调用时都将被引用为返回类型。

对于Typescript @ 3,这也适用:

class Model {
  save(): this {
    // save the current instance and return it
  }
}