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

Kin*_*sin 5 javascript generics inheritance constructor typescript

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

// get the clone
const clone = o1.clone();
Run Code Online (Sandbox Code Playgroud)

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

那么如何调用Child其基类中的构造函数呢?

也尝试了这个

Tit*_*mir 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);
    }   
}
Run Code Online (Sandbox Code Playgroud)

  • 从来不知道我可以将 `this` 设置为返回类型。感谢您的解决方案。经过多次尝试后,我对设置括号和转换“constructor”而不是“this”感到有些困惑。 (2认同)