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

时间:2017-08-24 20:28:56

标签: javascript typescript generics inheritance constructor

在我的打字稿中,我试图通过基类中的方法创建/克隆子对象。这是我的(简化)设置。

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

1 个答案:

答案 0 :(得分:6)

您可以使用new运算符调用构造函数,这似乎有效。此外,我会使用this作为返回类型,以便clone方法将返回派生类型而不是基类型

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