Calling a constructor from a derived type using this in typescript

In my typescript, I am trying to create / clone a child object using a method in the base class. This is my (simplified) setup.

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

Now I will create a new object

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

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

The constructor hits (but it's just a function call), which means that a new object has not been created. When used return Child.prototype.constructor(props)instead, I get my new object.

So how can I call the constructor of the Childbase class in it?

Also tried this

+4
source share
1 answer

, , , . 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);
    }   
}
+5

Source: https://habr.com/ru/post/1684410/


All Articles