继承类的 typescript 返回类型

标签 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 类型?

最佳答案

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

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();

d2Derived 类型,而d3DerivedAgain 类型,正如预期的那样。

关于继承类的 typescript 返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42344459/

相关文章:

html - 将页脚添加到 Angular Material Datepicker

javascript - Uncaught ReferenceError : define is not defined typescript

typescript - 使 lodash typings 的 defaultTo 方法与 TypeScript 编译器的 strictNullChecks 兼容

javascript - TS2304 : Cannot find name '__decorate' , '__metadata' 和 '__extends'

reactjs - 如何在 Material ui Popper 中输入过渡 Prop

typescript - 为什么我收到“typings WARN deprecated <packagename> is deprecated (updated,replaced or returned)”

javascript - 部分类型的参数不能分配给类型的参数

Angular v4 : Search by name with observable

angular - 如果变量 {{image}} 为空,则定义默认图像

visual-studio - angular 2 - PrimeNg teamcity/visual Studio 编译失败(不包括 node_modules)