如何在打字稿的基类中创建相同类型的实例

Fli*_*ion 1 inheritance types typescript

如果B扩展了A,A是否可以定义创建新B的方法?

class SetA {
   constructor(public items:any[]) {
   }
   createNew(items){
      return new *typeof this*(items); //<-- insert actually working magic here
   }
   clone(){
      return this.createNew(this.items);
   }
}
class SetB extends SetA { }

var x = new SetB([1,2,3]);
x.clone(); //<-- returns a new SetB
Run Code Online (Sandbox Code Playgroud)

Nit*_*mer 6

干得好:

type SetConstructor<T extends SetA> = {
    new (items:any[]): T;
}

class SetA {
   constructor(public items:any[]) {}

   createNew(items): this {
      return new (this.constructor as SetConstructor<this>)(items);
   }

   clone(){
      return this.createNew(this.items);
   }
}
Run Code Online (Sandbox Code Playgroud)

操场上的代码

所述的返回类型createNew的方法是this它是多态此类型