这就是我要做的事情:
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的克隆方法的返回类型应该是Derived类型的什么?
答案 0 :(得分:7)
我真的希望有更好的方法,但这就是我现在所做的事情:
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
的类型为Derived
,d3
的类型为DerivedAgain
,正如预期的那样。