typescript返回继承类的类型

时间:2017-02-20 12:20:23

标签: typescript typescript-typings

这就是我要做的事情:

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类型的什么?

1 个答案:

答案 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的类型为Derivedd3的类型为DerivedAgain,正如预期的那样。