Reputation: 3870
This is what I'm 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 the return type of the clone method for d2 to be of type Derived?
Upvotes: 16
Views: 6384
Reputation: 1717
I really hope there is a better way, but here is what I currently do:
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();
d2
is of type Derived
, and d3
is of type DerivedAgain
, as expected.
Upvotes: 20