typescript继承类的返回类型

9jyewag0  于 2023-02-20  发布在  TypeScript
关注(0)|答案(1)|浏览(134)

这就是我要做的

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,clone方法的返回类型应该是什么?

b09cbbtk

b09cbbtk1#

我真的希望有更好的方法,但以下是我目前所做的:

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,正如预期的那样。

相关问题