Create a TypeScript class object with specified constructor arguments

I've been working on a function that is supposed to execute the init method of a class and then return an instance of that class. However, I'm running into issues with maintaining the constructor and class types.

This is what I have tried so far:

class Test {
  constructor(a: number, b: string, c?: number[]) {}

  protected init() {}
}

export function instantiateWithInit<Type extends new (args: any) => { init: () => any }>(
  clazz: new (args: ConstructorParameters<Type>) => InstanceType<Type>,
  ...args: ConstructorParameters<Type>
) {
  const instance = new clazz(args);
  instance.init();
  return instance;
}

instantiateWithInit(Test, "");

However, the return type only includes the init method and I'm also encountering an error related to parameter matching in the type constructor:

Argument of type 'typeof Test' is not assignable to parameter of type 'new (args: [args: any]) => { init: () => any; }'.
  Types of construct signatures are incompatible.
    Type 'new (a: number, b: string, c?: number[]) => Test' is not assignable to type 'new (args: [args: any]) => { init: () => any; }'.ts(2345)

Answer №1

One challenge present in this scenario is the requirement for the function to only take a single argument in its constructor. By utilizing the spread operator, it becomes possible to resolve this particular issue.

In order to successfully implement your concept, I found it necessary to alter the function definition in the following manner:


class Example {
    constructor(x: number, y: string, z?: number[]) { }

    public start() { }
}

export function initializeWithStart<
    E extends { start(): any },
    X extends any[]
>(
    className: new (...args: X) => E,
    ...arguments: X
) {
    const instance = new className(...arguments);
    instance.start();
    return instance;
}

const xyz = initializeWithStart(Example, 7, "");
// ^ xyz is of type Example
// Additionally, the input arguments are validated (which is why the 7 was added)

I must acknowledge that TypeScript can pose challenges when using extends within function definitions.

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 download of package-lock.json is not initiated for a linked GitHub URL

I currently have two projects on GitHub. One is named "mylibrary" and the other is "test-project." In my "test-project," I have linked "mylibrary" using its GitHub URL in the package.json file as shown below. dependencies: { "mylibrary": "git+ssh://& ...

Error message: "When using Webpack 4 with Bootstrap, a TypeError occurs where property 'jquery' is read as undefined."

I've recently delved into the world of webpack and everything seems to be running smoothly. However, when I run my webpack app, I encounter the following error within Bootstrap: var version = $.fn.jquery.split(' ')[0].split('.'); ...

What criteria should I consider when selecting a JavaScript dependency framework?

When it comes to installing dependencies, how do I determine whether to use NPM or Bower? For example, what distinguishes npm install requirejs --save-dev from bower install requirejs --save-dev? Is there a recommended method, or any guidelines for makin ...

Uploading a file with AngularJS and storing it in a database

I have been attempting to implement ngFileUpload in order to upload images and store them in a database – specifically, a mongoLab database that accepts JSON objects which can be posted using this syntax: $http.post('myMongoName/myDb/myCollection/ ...

enhancing angular directives with data binding while replacing HTML content inside the compile function

I am currently attempting to develop a directive that will substitute an input field with a custom-made input field. Unfortunately, I am encountering challenges with getting the data binding to function properly, as the model does not display in the direct ...

Saving the subtracted value from a span into a cookie until the checkbox is unchecked - here's how to

I am working on a piece of code that includes numeric values within a span. When the checkbox is clicked, it subtracts 1 from the main value, essentially reducing the total value. How can I achieve this so that even after the form is submitted, the deducte ...

The functionality of ngModel seems to be malfunctioning when used within select options that are generated inside

I'm currently working on dynamically adding options to an HTML select element within a for loop. I am using [(ngModel)] to get the selected option, but initially no option is pre-selected. Here's a snippet of the code: <table align="center"& ...

How can I pre-fill an AutoModelSelect2Field with static information in Django using the django-select2 library?

I am currently using a field similar to the one below: class ContactSelect(AutoModelSelect2Field): queryset = Contact.objects.all() search_fields = ['name__contains'] to_field = 'name' widget = AutoHeavySelect2Widget W ...

Tips for incorporating conditional statements within return statements in functional components in React JS

I need to display the login page if the user is not logged in, otherwise show the forbidden 403 page. Since I'm using a functional component, I can't use render(). return forbidden === false ? ( <> <Container maxWidth="x ...

Encountering an "Unspecified Reference Error" while attempting to retrieve data from an API in your

I've been attempting to utilize a mock API from in order to fetch data for my Next.js application. However, I am consistently encountering an undefined reference error, despite following the code snippet provided in the official Next.js documentation ...

Which is better for creating a gradual moving background: Javascript or CSS?

I'm attempting to discover how to create a background image that scrolls at a slower pace than the page contents. I'm currently unsure of how to achieve this effect. A great example of what I'm aiming for can be seen here Would this require ...

React is having trouble resolving the path required

Having an issue with the tracking-js library in my project. I'm using React and despite checking my package.json and confirming that the module is installed, I keep receiving errors indicating that the module cannot be found. This is how I am attempti ...

AngularJS - how to dynamically delete a directive from an element

Looking for a way to dynamically add or remove directives from compiled and linked elements? I have a page with numerous inputs and want to disable all of them if a specific flag is set. The conventional method using jQuery's element.prop('disabl ...

Sliding with JavaScript

I'm looking to develop a unique web interface where users can divide a "timeline" into multiple segments. Start|-----------------------------|End ^flag one ^flag two Users should be able to add customizable flags and adjust their position ...

Verifying the name's uniqueness and disregarding it in case of any alterations

I am currently working on a form that includes a modal to allow users to modify their name and email address. The issue I am facing is that the form sends a request to the server to check for unique values in all cases. While this is appropriate when creat ...

What's the best way to incorporate necessary styles into text using particular fonts?

Is there a way to set letter spacing and word spacing for text on my website with the font 'classylight'? Adding classes to each post in the site map seems like a lengthy process. To save time, I attempted to use the attribute*=style property to ...

Oops! Looks like there was an error. The text strings need to be displayed within a <Text> component in the BottomTabBar. This occurred at line 132 in the

My app includes a bottomTab Navigation feature, but I encountered an error: Error: Text strings must be rendered within a <Text> component. This error is located at: in BottomTabBar (at SceneView.tsx:132) in StaticContainer in StaticCont ...

Unable to expand or collapse rows in ng-table

Looking to implement an expand and collapse feature for ng-table, where clicking on a row should expand it to show more detail. However, currently all rows expand on click. Any ideas on how to achieve this? Any assistance would be greatly appreciated, tha ...

Create original identifiers for dynamically generated material

I have developed a custom invoice tool that has the capability to dynamically add rows. Here is the code snippet responsible for generating new rows: $("#addrow").click(function(){ $(".item-row:last").after('<tr class="item-row"><td> ...

Angular JS effectively prevents redundant data from being displayed to users when scrolling infinitely while also efficiently removing DOM elements for previous data

I'm currently working on implementing AngularJS Infinite Scroll without using jQuery. My goal is to display the first 3 data items when the page loads and then load the next 3 data items from a JSON array object as the user scrolls. The issue I am fac ...