How to retrieve the constructor type of a clean class in TypeScript

Is there a way to use the typeof operator to retrieve the constructor type from a class, specifically when dealing with a dictionary of classes? When trying to use it on a dictionary of classes like Modules[T], the compiler interprets it as (typeof Modules)[T] instead of obtaining the actual type of Modules[T].

class A { }

class B { }

abstract class Modules {
    public a!: A;
    public b!: B;
}

// Error: Type 'T' cannot be used to index type 'typeof Modules'
function addModule<T extends keyof Modules>(key: T, ModuleCtor: typeof Modules[T]) {
    let module = new ModuleCtor();
}

addModule('a', A);

// Works but loses the constructor arguments type
function addModule2<T extends keyof Modules>(
    key: T,
    ModuleCtor: new (...args:any[]) => Modules[T]
) {
    let module = new ModuleCtor();
}

addModule2('a', A);

Playground url

Update

As Aleksey mentioned, the typeof operator only works on values. Since classes are considered as actual values in JavaScript, what I have here are pure types. Essentially, I am searching for a solution that functions similar to typeof Class (value), which would enable me to retrieve the precise type of a constructor (including its arguments) for a pure class type.

Answer №1

Your main issue lies in understanding that Typescript types are primarily shaped by interfaces, rather than being strict, rigid types.

For instance, consider the scenario where -> class A { } and class B { } are essentially the same Type.

To differentiate between A & B in your example, we need to make them unique so Typescript can distinguish them.

Otherwise, you could mistakenly do -> addModule('a', B);, which I'm assuming you want to avoid.

For example:

class A { A?:string }
class B { B?:string }

In this revised version, the types of class A & B have been changed to be distinct. In a real application, their methods would likely vary as well, eliminating the need for such dummy declarations like A?:string.

Furthermore, we must establish the structure of our constructor. If it's empty, a simple model would be ->

type Construct<T> = new () => T;

After implementing these changes, our final code appears as follows ->

class A {
    A?: string
}

class B {
    B?: string
}

class Modules {
    a!: A;
    b!: B;
}

type Construct<T> = new () => T;

function addModule<T extends keyof Modules, C extends Construct<Modules[T]>>(key: T, ModuleCtor: C) {
  const x = new ModuleCtor()
}

var a = addModule('a', A)

//Argument of type 'typeof B' is not assignable to parameter of type 'Construct<A>'.
var a = addModule('a', B)

Playground

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

The variable fails to receive a value due to an issue with AJAX functionality

I am struggling to figure out what's causing an issue with my code. I need to store the result of an AJAX request in a variable, specifically an image URL that I want to preload. $.ajax({ type: "POST", url: 'code/submit/submi ...

Show the ajax appended html only after reaching a specific threshold

I am currently utilizing AJAX to fetch additional results from my database. Below is the basic script I am using: $('#loadmorebuilds-div').click(function() { $.ajax({ url: 'includes/loadmorebuilds.php?type=' + type + &ap ...

What is the best way to showcase a QR code on a mesh using three.js?

I utilized the QRcode library available at to try and showcase it on a mesh object as a texture using the following code: var qrcode = new QRCode( "test", { text: "http://jindo.dev.naver.com/collie", width: 128, height: 128, colorDark : " ...

The GitHub process is ongoing and not ending

I have developed a GitHub workflow that utilizes a node script. To test it, I set it up to run on manual trigger. Below is the code snippet of my workflow file: on: workflow_dispatch: inputs: logLevel: description: 'Log level&apos ...

Issues with displaying Bootstrap 5 second toast notifications

Hey there, I'm facing an issue with getting the second toast to display properly. Here is the HTML: <div class="toast-container position-fixed bottom-0 end-0 p-3"> <!-- FIRST --> <div class="toast" role="aler ...

Ways to verify if JSON response is null using jquery

$.getJSON(url, function(json) { var output = ''; $.each(json, function(i,d) { if(d.DESCRIPTION == 'null'){ console.log("Its empty"); } var description = d.DESCRIPTION; output += '<tr><td>&apo ...

choose among various options in Javascript

I'm currently using PHP and AJAX to create a basic CRUD system. I want to display a form with three buttons: Grabar, Modificar, and Eliminar. The issue I'm facing is determining the action to take based on which button is clicked. For instance, c ...

Updating the Position of an Element in ElectronJS (e.g. Button, Label, etc)

Is there a way to change the positioning of a button in a window using JavaScript and Electron? I am trying to create new input boxes next to existing ones, but they always appear below the last one created. Is it possible to specify x and y coordinates fo ...

What is the process for streaming video (images) to an HTML5 client using C#?

Currently, I am utilizing C# to fetch continuous bitmaps (video) from an ipcamera. These bitmaps are then converted to base64string and sent (JSON) to an HTML5 canvas, which is responsible for rendering the images. During my research, I came across a meth ...

Obtain the PHP hyperlink value from an AJAX response

I am trying to create a link action to the controller in Codeigniter after receiving a response from AJAX. I need a variable from the AJAX response to include in the link to the controller, where an update process will be carried out. I attempted to use a ...

The synchronization between the First Column Scroll and Table Filter Function is out of alignment

I haven't coded for a while and my knowledge of JavaScript is still in its early stages, so please excuse me if this question seems a bit naive. Essentially, I've created code that filters an HTML table based on the items in the first column. Th ...

Analyzing and swapping objects within two arrays

Looking for a better way to append an array of objects customData to another array testData? If there are duplicate objects with the same name, replace them in the resulting array while maintaining their order. Here's my current approach in ES6 - any ...

Iterate through a collection of objects and organize the data in a specific way

Within the data structure of my API response, I am attempting to iterate through an array of objects under the items key. Each value inside these objects needs to be formatted based on the corresponding format type specified in the header key. To assist wi ...

Is there a way to sort through and select specific files for download within the blueimp jquery download software?

Currently attempting to utilize the Blueimp jQuery File Upload File software https://github.com/blueimp/jQuery-File-Upload. After exploring the wiki and documentation, I have not been able to find a solution on how to filter the downloadable files. This t ...

Most secure methods to safeguard videos from unauthorized downloading

How can I increase the security measures to prevent users from easily downloading videos from my website? While I understand that it is impossible to completely stop downloads, I am looking for ways to make it more challenging than just a simple right-cl ...

In what situations is it appropriate to utilize the getInnerHtml() method?

Within Protractor, an ElementFinder instance has access to the getInnerHtml() method: var elm = element(by.id("myid")); expect(elm.getInnerHtml()).toEqual("test"); Interestingly, this method is not included in the official API list. Can you think of any ...

Can someone help me troubleshoot the issue with my submit button's onclick function?

I am currently working on a project where I have a content box enclosed in a div tag. Within this content box, there are paragraphs with unique IDs for individual styling rules. I have set margins, padding, and other styles accordingly. At the bottom of th ...

Enable or disable dropdown based on selected radio button status

I need the dropdown to be disabled unless the radio button labeled prov is selected. It should only be enabled when prov is chosen. I attempted to create a demo, but it's not functioning correctly and I can't figure out why. HTML: <td colsp ...

What causes my code to break completely when I import something?

My chrome extension has a simple function that retrieves a user's selected text using the Chrome Tabs API. I am looking to integrate a Hugging Face API in the future, but I am facing an issue. Whenever I try to import the necessary model, the Chrome T ...

Concealing video when the source is inaccessible

I am facing an issue with a video element that retrieves its source from a database. The video tag is placed inside a repeater that is bound to the database. My goal is to hide the video if the source is not found in the database. I attempted to use Javasc ...