Flion Flion - 2 months ago 7
TypeScript Question

How to create an instance of the same type in a baseclass in typescript

If B extends A, can A define a method that creates a new 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

Answer

Here you go:

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);
   }
}

(code in playground)

The return type of the createNew method is this which is the Polymorphic this types.

Comments