Using TypeScript, you can access the constructor of a derived type by calling it with the

In my TypeScript project, I am attempting to generate or duplicate a child object using a method within the base class. Here is my simplified code setup:

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

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

    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 am about to instantiate a new object:

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

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

The constructor is called (but it's just the function call), indicating that a new object is not being created. When I use

return Child.prototype.constructor(props)
instead, I am able to create a new object.

So, how can I invoke the constructor of Child within its base class?

I have also explored this as a potential solution.

Answer №1

One way to call the constructor is by using the new operator. Additionally, it's advisable to specify this as the return type in order for the clone method to return the derived type instead of the base type.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reduce the density of x-axis labels in highcharts

Do you have any input on Highcharts? This chart belongs to me: https://i.sstatic.net/OAjJJ.png I am looking to reduce the density of x-axis labels, similar to the y-axis. Your assistance is greatly appreciated. Edit: for instance, take a look at this ...

A guide on displaying data from objects containing arrays in React using TypeScript

Hey there! I'm currently facing a challenge in rendering values within an object containing arrays. Let me show you an example of the object structure: data { info1: [{note: "this is note 1", status: true}], info2: [{note: "this i ...

`Inquiry into AJAX form submission problem`

Here is the HTML markup and JS code for my signup page. I encountered an issue where, if I leave all text inputs blank and click submit for the first time, it validates and shows an error message. However, when I click submit a second time, it directly sen ...

The attribute 'location' is not found in the 'File' data type

Recently, I made the switch from using multer to multer-s3 in my project. I have updated the controllers accordingly to store the "location" instead of the "filename". However, I am encountering a typescript error. At the moment, I am utilizing Localstack ...

Building a custom login page with axios in a react-redux application

I've encountered an issue with my login page. When I click the submit button, it does not redirect to the main Dashboard page. Check out the code below for authentication/login.js: import React, { Component } from 'react' import { Field, ...

Submit Form Without Reloading -- and successfully submit it

I'm working on a form submission that triggers AJAX and PHP to load data without the need for page reloading. html/php <form method="POST"> <button type="submit" name="image1"> <button type="submit" name="image2"> <button ...

Calculating the size of an array based on its attributes

Hey there, I'm working with an array containing attributes and need to determine its length. In this particular case, the array should have a length of 2 since there are only two "items" present. {"items":[{"value":"2","valor":0,"name":"Limpeza"}, {" ...

Using a nested loop in Javascript to fetch JSON data

My goal is to display Categories and their corresponding subcategories in a specific order. However, my current method of using loops within loops is not producing the desired outcome: Category(Mobile) Category(Laptop) Subcategory(Iphone4) Subcategory(Iph ...

Leverage the useRef hook with React Draggable functionality

Having recently delved into coding, I find myself navigating the world of Typescript and React for the first time. My current challenge involves creating a draggable modal in React that adjusts its boundaries upon window resize to ensure it always stays wi ...

What is the best way to create a moving line using EaselJS and TweenJS?

My objective is to animate a line from point A to point B using the Tween function. I am utilizing the EaselJS drawing library and TweenJS for animation. Can I achieve this by using the moveTo function to animate a straight line from point A to point B? ...

What is the process of permanently modifying an HTML document using JavaScript?

I'm interested in creating a basic comment section using JavaScript. Here is the structure of the form : <form> <textarea cols="50" rows="10" placeholder="Share your thoughts ..." id="theComment"></textarea><br/> < ...

`How can I manage my electron.js application effectively?`

As a newcomer to electron.js, I have successfully created a game using html, css, and javascript that currently runs offline on the client side. However, I am now looking for a way to access, analyze, and make changes to this app. One solution could be lo ...

Display a few HTML elements sourced from a different online platform

I am trying to extract a specific value from a span element on another website and render it on my own website using either a GET/FETCH request or some other method. Currently, I have this code but I am struggling to extract the data I need. The data I am ...

What is the best method for retrieving a child control from a TR element?

I am facing an issue with a hidden field inside each Tr in my template: <ItemTemplate> <tr style="" class="ui-selectee trClass ui-widget-content"> <td style="width: 100px"> <asp:HiddenField ID="idField" runat=" ...

Why does Angular not reset form after ng-click event?

Something seems off with my form reset after a ng-click event, am I missing something? I can successfully submit the form, but it doesn't automatically reset. Here is the error message I receive: angular.js:12701 POST 500 (Internal Server Error ...

Remove all spaces from input fields in angular Typescript, excluding the enter key

I've encountered an issue where the code below removes all spaces, but it's also removing the enter key. Is there a way to remove only spaces and not affect the enter key? static stripDoubleSpaces(str: string): string { if (!!str) { ...

Enhancing Angular functionality with the addition of values to an array in a separate component

I need help with adding a value to an array in the 2nd component when a button in the 1st component is clicked. I am working on Angular 4. How can I achieve this? @Component({ selector: 'app-sibling', template: ` {{message}} <butt ...

Tips for testing nested HTTP calls in unit tests

I am currently in the process of unit testing a function that looks like this: async fetchGreatHouseByName(name: string) { const [house] = await this.httpGetHouseByName(name); const currentLord = house.currentLord ? house.currentLord : '957'; ...

Encountering Error 203 while trying to establish a connection between Angular and Django Rest Api

I'm currently working on a project that involves creating a contacts system, but I've been encountering errors when trying to list them. Interestingly, I can successfully perform CRUD operations using Postman with the API. One of the messages I ...

View a photo in advance of its upload using VUEjs

Although this question has been raised before, I am struggling with implementing the code in vuejs. Despite my efforts, I have not been able to achieve any results yet. I have included my code below. Could someone please assist me? Here is my code. Thanks ...