这就是我想要做的:
class Base{
    clone(){
        //return new instance of the inherited  class 
    }
}
class Derived extends Base{
}
const d1=new Derived();
const d2=d2.clone; // I want d2 to be of type Derived
d2的clone方法的返回类型应该是Derived类型的返回类型?
作为TypeScript的新手,在实例化子类类型的基类中实现静态工厂的最佳方法是什么.例如,考虑findAll基础模型类中的方法:
class BaseModel {
  static data: {}[];
  static findAll() {
    return this.data.map((x) => new this(x));
  }
  constructor(readonly attributes) {
  }
}
class Model extends BaseModel {
  static data = [{id: 1}, {id: 2}];
  constructor(attributes) {
    super(attributes);
  }
}
const a = Model.findAll();  // This is BaseModel[] not Model[]
这返回BaseModel[]而不是Model[].
免责声明:我发现很难在问题标题中概括问题,所以如果您有更好的建议,请在评论中告诉我。
让我们看一下以下简化的 TypeScript 类:
class Model {
  save():Model {
    // save the current instance and return it
  }
}
该类Model有一个save()返回自身实例的方法: a Model。
我们可以Model这样扩展:
class SomeModel extends Model {
  // inherits the save() method
}
因此,SomeModel将继承save(),但它仍然返回 a Model,而不是 a SomeModel。
有没有一种方法,也许使用泛型,将save()in的返回类型设置SomeModel为SomeModel,而不必在继承类内部重新定义它?