从派生类型调用构造函数通过这在打字稿中

从派生类型调用构造函数通过这在打字稿中

问题描述:

在我的打字稿中,我试图通过基类中的方法创建/克隆子对象。这是我的(简化)设置。从派生类型调用构造函数通过这在打字稿中

abstract class BaseClass<TCompositionProps> { 
    protected props: TCompositionProps; 

    protected cloneProps(): TCompositionProps { return $.extend(true, {}, this.props); } // can be overwriten by childs 

    constructor(props: TCompositionProps){ 
     this.props = props; 
    } 

    clone(){ 
     const props = this.cloneProps(); 
     return this.constructor(props); 
    } 
} 

interface IProps { 
    someValues: string[]; 
} 

class Child extends BaseClass<IProps>{ 
    constructor(props: IProps){ 
     super(props); 
    } 
} 

现在,我要创建一个新的对象

const o1 = new Child({someValues: ["This","is","a","test"]}; 

// get the clone 
const clone = o1.clone(); 

构造被击中(但它只是调用函数),这意味着没有创建新的对象。 当使用return Child.prototype.constructor(props)而不是我得到我的新对象。

那么我怎样才能在它的基类中调用Child的构造函数呢?

也试过this

您可以用新的运营商,这似乎工作调用构造函数。此外,我会用this返回类型,这样的克隆方法将返回派生类型不是基本类型

abstract class BaseClass<TCompositionProps> { 
    protected props: TCompositionProps; 

    protected cloneProps(): TCompositionProps { return $.extend(true, {}, this.props); } 

    constructor(props: TCompositionProps){ 
     this.props = props; 
    } 

    clone() : this{ 
     const props = this.cloneProps(); 
     return new (<any>this.constructor)(props); 
    } 
} 
+0

从来不知道,我可以设置'this'为返回类型。感谢这个和解决方案。经过多次尝试后,我对设置圆括号和铸造'constructor'而不是'this'感到困惑。 – KingKerosin