A guide to teaching TypeScript to automatically determine the type of dynamic new() calls

One of the challenges I'm facing involves dynamically creating subclasses and ensuring that the factory function is aware of the subclass's return type.

While I can currently achieve this using a cast, I am exploring options to infer the return type without requiring such explicit casting.

class Greetings {
  x = 5;
}

class Greetings2 extends Greetings {
  y = 10;
}

class Greetings3 extends Greetings {
  z = 15;
}

function generate<T extends typeof Greetings>(constructor: T): InstanceType<T> {
  // Without this cast, the code won't compile successfully
  return new constructor() as InstanceType<T>;
}

// This fails due to incorrect constructor type
const g1 = generate(Number);
const g2 = generate(Greetings2);
console.log(g2.y); // no error
const g3 = generate(Greetings3);
console.log(g3.z); // no error

Answer №1

Have you considered making the class instance generic instead of the static side or constructor function? This approach should work for you, as shown here:

class Hello { 
  a = 1;
}

class Hello2 extends Hello{ 
  b = 2; 
}

class Hello3 extends Hello { 
  c = 3; 
}

function create<T extends Hello>(ctor: new() => T) {
  return new ctor()
}

const h1 = create(Number); // error
const h2 = create(Hello2); // h2: Hello2
console.log(h2.b); // no error
const h3 = create(Hello3); // h3: Hello3
console.log(h3.c); // no error

If necessary, you could specify additional arguments to be passed using something like

create<T extends Hello>(ctor: new(...args: any[]) => T)
or in a more specific way.

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

Attempting to connect to "http://localhost:4242/webhook" was unsuccessful due to a connection refusal when trying to dial tcp 127.0.0.1:4242

In my next.js 13 project, I am integrating stripe with TypeScript and configuring the app router. To create a stripe event in my local machine, I ran stripe listen --forward-to localhost:4242/webhook, but now I am encountered with the error message stripe ...

What would be the counterpart of setLocale in Yup for the zod library?

How can I set default custom error messages for Zod validation? If I want to use i18n for error messages in Yup, I would do the following: import { t } from "i18next"; import * as yup from "yup"; import "./i18next"; yup.setL ...

Error: The AppModule encountered a NullInjectorError with resolve in a R3InjectorError

I encountered a strange error in my Angular project that seems to be related to the App Module. The error message does not provide a specific location in the code where it occurred. The exact error is as follows: ERROR Error: Uncaught (in promise): NullInj ...

Using i18next to efficiently map an array of objects in TypeScript

I am currently converting a React project to TypeScript and using Packages like Next.js, next-i18next, and styled-components. EDIT: The information provided here may be outdated due to current versions of next-i18next. Please check out: Typescript i18ne ...

What is the process for defining custom properties for RequestHandler in Express.js middleware functions?

In my express application, I have implemented an error handling middleware that handles errors as follows: export const errorMiddleware = (app: Application): void => { // If the route is not correct app.use(((req, res, next): void => { const ...

Struggling to integrate Docker compatibility into an established NextJS project, encountering the frustrating "stat app/.next/standalone: file does not exist" message

I'm currently in the process of enhancing my existing NextJS + TypeScript project with Docker support and preparing to deploy it on Google Cloud Run. To achieve this, I've been referring to a helpful guide available at: https://github.com/vercel/ ...

Steps for utilizing field labels to transmit values in Protractor

Could someone offer guidance on how to send values using field labels? I understand that it's generally not recommended to use labels for sending values since they can change, but in my case, the labels remain constant. I have attached screenshots of ...

Set panning value back to default in Ionic

I need assistance with resetting the panning value. Essentially, I would like the panning value to return to 0 when it reaches -130. Below is my code snippet: swipeEvent($e) { if ($e.deltaX <= -130) { document.getElementById("button").click(); ...

Tips for determining the datatype of a callback parameter based on the specified event name

Let's say we have the following code snippet: type eventType = "ready" | "buzz"; type eventTypeReadyInput = {appIsReady: string}; interface mysdk { on:(event: eventType, cb: (input: eventTypeCallbackInput) => void) => void } mysdk.on("ready", ...

Transferring data between pages in Next JS using App Route and Typescript

Seeking assistance to extract data from an array on one page and display it on another page. I am working with NextJs, Typescript, and AppRoute. Code in app/page.tsx: import Image from 'next/image' import Link from 'next/link' const l ...

A guide to submitting forms within Stepper components in Angular 4 Material

Struggling to figure out how to submit form data within the Angular Material stepper? I've been referencing the example on the angular material website here, but haven't found a solution through my own research. <mat-horizontal-stepper [linea ...

Tips for creating fixed first two columns in a table using React and TypeScript

I need a table where the first two columns stay fixed as headers while scrolling through the body of the table. ...

What is the proper way to address the error message regarding requestAnimationFrame exceeding the permitted time limit?

My Angular application is quite complex and relies heavily on pure cesium. Upon startup, I am encountering numerous warnings such as: Violation ‘requestAnimationFrame’ handler took 742ms. Violation ‘load’ handler took 80ms. I attempted to resolve ...

A guide on efficiently utilizing combineLatest and mergeMap for handling multiple subscriptions

As I continue to delve into the world of rxjs, I've encountered an issue with managing multiple subscriptions. Specifically, I'm struggling to extract an ID from a response in order to correctly associate photos with products. create(product) { ...

loop through an intricate JSON schema using Angular 5

I've been trying to figure out how to iterate a complex JSON in Angular 5. I came across the pipe concept, but it doesn't seem to work with JSON data like the one below. I'm trying to create an expandable table using this type of data, but I ...

What is preventing type guarding in this particular instance for TypeScript?

Here is an example of some code I'm working on: type DataType = { name: string, age: number, } | { xy: [number, number] } function processInput(input: DataType) { if (input.name && input.age) { // Do something } e ...

How to send variables to a function when a value changes in TypeScript and Angular

As someone who is new to Angular and HTML, I am seeking assistance with the following code snippet: <mat-form-field> <mat-select (valueChange)="changeStatus(list.name, card.name)"> <mat-option *ngFor="let i of lists"> {{i.name}} ...

Caught up: TypeScript not catching errors inside Promises

Currently, I am in the process of developing a SPFx WebPart using TypeScript. Within my code, there is a function dedicated to retrieving a team based on its name (the get() method also returns a promise): public getTeamChannelByName(teamId: string, cha ...

How to invoke a function from a different controller in Ionic 2

Is it possible to call a function in another controller within Ionic 2? Here is my code where I want to call the loadPeople function in the tab controller. home.ts import { Component } from '@angular/core'; import { NavController } from ' ...

Leverage the specific child's package modules during the execution of the bundle

Project Set Up I have divided my project into 3 npm packages: root, client, and server. Each package contains the specific dependencies it requires; for example, root has build tools, client has react, and server has express. While I understand that this ...