Steps for creating an instance of the same type within a base class in TypeScript

When B extends A, is it possible for A to define a method that generates a new instance of B?

class SetA {
   constructor(public items:any[]) {
   }
   createNew(items){
      return new *typeof this*(items); //<-- insert actual implementation here
   }
   clone(){
      return this.createNew(this.items);
   }
}
class SetB extends SetA { }

var x = new SetB([1,2,3]);
x.clone(); //<-- creates a new SetB object

Answer №1

Below is the solution:

type SetConstructor<T extends SetA> = {
    new (items:any[]): T;
}

class SetA {
   constructor(public items:any[]) {}

   createNew(items): this {
      return new (this.constructor as SetConstructor<this>)(items);
   }

   clone(){
      return this.createNew(this.items);
   }
}

(code in playground)

The createNew method has a return type of this, leveraging Polymorphic this types.

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

Simple steps to emphasize a table cell in Angular 2

Essentially, I have a table structured as shown below <table> <tr> <td>Date</td> <td>Time</td> <tr> <table> The goal is to make both the date and time clickable within this table. When clicking on the date, ...

Encountering an unsecured WebSocket connection when trying to access the Neo4J endpoint post deployment on Firebase

I have developed an application using Neo4j, but when I try to host the app in Firebase, I encounter the following error: The page at 'https://yourwebsite.com' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint &a ...

Encountering errors while setting up routes with Browser Router

When setting up a BrowserRouter in index.tsx, the following code is used: import './index.css'; import {Route, Router} from '@mui/icons-material'; import {createTheme, ThemeProvider} from '@mui/material'; import App from &ap ...

Incorporate the leaflet Draw feature into your Angular 2 application

I am a newcomer to Angular2, created using Cli. While I successfully imported Leaflet into my Angular2 project without any Angular2 directives, I am struggling to do the same with the Leaflet Draw extension. I haven't been able to make Draw work. In e ...

The unbeatable combination of Vuex and Typescript

I am currently in the process of converting a JavaScript project to TypeScript. However, I have encountered a type error when attempting to integrate Vuex with Vue. import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); https://i.sstatic.net/e7 ...

Creating an optional item in a fixed array of Promises with Typescript

I am encountering an issue with a variable called promises. Here is what it looks like: const promises: | [Promise<boolean>, Promise<boolean>] | [Promise<boolean>, Promise<boolean>, Promise<{ currency: str ...

Implementing the withAuthenitcationProps method in all page.tsx files to integrate Amazon Cognito authentication

I have been working on my Next.js app and wanted to share the project structure with you: ├── README.md ├── amplify │ ├── #current-cloud-backend │ ├── README.md │ ├── auth │ ├── backend │ ├── cl ...

I am interested in identifying the TypeScript code within my library that is not being utilized. Any suggestions on how to achieve this?

What is the method to enable code lenses for TypeScript and identify sections with 0 references? Shown in this example image, which settings can indicate 0 references (similar to the grey font in the picture)? ...

Retrieving Age from HTML5 Date Input in Angular 2+

I need assistance in calculating the age from a date input in an existing form using HTML5 and Angular. I want to achieve this without requiring the user to click anything. Although I am able to retrieve the date, the format is causing issues with my code ...

What sets apart gzip from x-gzip content? And how can I decompress x-gzip specifically? zlib appears to be struggling

One of my npm libraries, named "by-request", has the ability to auto-decompress web content. A snippet of code from this library that handles auto-decompression is shown below: if (!options.dontDecompress || !binary) { if (contentEncoding ...

Ways to avoid using a specific type in TypeScript

Imagine having a class that wraps around a value like this: class Data<T> { constructor(public val: T){} set(newVal: T) { this.val = newVal; } } const a = new Data('hello'); a.set('world'); // typeof a --> Primitiv ...

What could be the reason for receiving an HttpErrorResponse when making a GET request that returns byte data

When using these headers, the API returns byte data as a response. let headers = { headers: new HttpHeaders({ 'Content-Type': 'application/octet-stream', 'responseType':'arraybuffer' as 'js ...

Implementing TypeScript in an Asp.net Core ReactJS application`s configuration

After using Visual Studio 2022 to create an asp.net core Reactjs project, I discovered that everything was written in javascript instead of typescript. Is there a way to switch this project over to typescript? ...

Issue with displaying selected value and options in Mat-select when using formarray - Reactive forms in Angular

I've been working on the code below to create dropdowns, but I'm having trouble getting the selected value and options to show up in the dropdowns. Can you help me figure out what's wrong with the code? Component code testForm: FormGroup; ...

What is the correct way to implement Axios interceptor in TypeScript?

I have implemented an axios interceptor: instance.interceptors.response.use(async (response) => { return response.data; }, (err) => { return Promise.reject(err); }); This interceptor retrieves the data property from the response. The re ...

How can I properly specify the type of a function for a complex object with index signatures in TypeScript?

Problem with Retrieving Specific Data from Mixed Object I'm encountering an issue with a function that is supposed to retrieve a specific piece of data within an object. The object contains a combination of known indexes and index signatures, which s ...

Transforming JavaScript code with Liquid inline(s) in Shopify to make it less readable and harder to understand

Today, I discovered that reducing JavaScript in the js.liquid file can be quite challenging. I'm using gulp and typescript for my project: This is a function call from my main TypeScript file that includes inline liquid code: ajaxLoader("{{ &ap ...

Guide on utilizing mongoose for handling multiple increment operations

Currently, I am developing a program that tracks different "accepts" and "denies". In this project, I am utilizing the findOneAndUpdate function from mongoose. However, I am encountering some issues with achieving the desired functionality. The data I am w ...

An unexpected loop is generated by Angular2's ngFor

Attempting to implement ngFor in Angular 2 rc-1, here is an example: @Component({ selector: 'myList', template: `<h2>Menu</h2> {{title}} <ul> <li *ngFor="let menu o ...

What is the method for incorporating a variable into a fragment when combining schemas using Apollo GraphQL?

In my current project, I am working on integrating multiple remote schemas within a gateway service and expanding types from these schemas. To accomplish this, I am utilizing the `mergeSchemas` function from `graphql-tools`. This allows me to specify neces ...