Typescript return type of inherited class

This is what I am trying to do:

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

What should be the return type of the clone method for d2 of type Derived?

+4
source share
1 answer

I really hope there is a better way, but here is what I am doing now:

class Base{
    clone(): this {
        return new (this.constructor as any)(); 
    }
}

class Derived extends Base {
}

class DerivedAgain extends Derived {

}

const d1=new Derived();
const d2 = d1.clone(); 
const d3 = new DerivedAgain().clone();

d2has a type Derived, but d3has a type DerivedAgain, as expected.

+2
source

Source: https://habr.com/ru/post/1670290/


All Articles