Explaining how to define a function parameter that accepts a class as an argument in TypeScript

I'm looking to develop a function that can take the class type (the class itself, not an instance) as a parameter and then instantiate an object based on that input.

Let me illustrate this with an example:

//All classes that could be passed as parameters must inherit from this base class
class Base { public name : string = ''; }

//These are some sample classes that might be used as parameters for the function
class Dog extends Base { constructor() { super(); console.log("Dog instance created"); } }
class Cat extends Base { constructor() { super(); console.log("Cat instance created"); } }

//The function should accept a class that inherits from 'Base' as a parameter and create an instance
function Example(param : ?????????) : Base //I need help determining the correct type for 'param'
{
    return new param(); //How can I instantiate an object here?
}

//If everything was working correctly, the desired output would be:
Example(Dog); //Logs "Dog instance created""
Example(Cat); //Logs "Cat instance created""

//With this functioning properly, we could do things like:
let x : Dog = Example(Dog);
let y : Cat = Example(Cat);

My main question: what should be the data type of the parameter for the 'Example' function? And how can I successfully generate an instance of that parameter within the function?

If this query resembles another question, I apologize - I just don't know the technical term for this functionality, making it challenging to find information online.

Answer №1

Here is an example that you might find helpful.

function Customize<U extends Original>(input: new () => U): U {
    return new input();
}

In this scenario, we are assuming that you have a type that is based on Original. Let's call this type U, and specify that it must be a subtype of Original by writing U extends Original.

We also understand that the parameter input will create an instance of type U without any arguments. This behavior can be described with new () => U.


To simplify, consider that a class possesses both an instance aspect and a static facet (also known as the "constructor" side). In your instance, Original, Custom1, and Custom2 individually represent the static facets.

For each of them, the static facet incorporates all specified static elements (none in this scenario), along with the construction signature. Your situation involves the Customize function which takes a constructor expecting no parameters, and generates a derivative of Original.

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

$(...).parentElement is not a function - Troubleshooting a Problem with WebDriver IO and TypeScript

Alright, the objective is simple. I need to ascend from the root to obtain its parent element. Following the webdriver documentation, it should resemble something like this: it('should retrieve the class from the parent element', async () => { ...

Is it possible in Typescript to determine whether an object or function was brought in through an "import * as myImport" declaration?

Currently, I am importing all exports from a file in the following way: import * as strings from "../src/string"; After that, I assign a function to a const based on a condition: const decode = (strings._decode) ? strings._decode : strings.decod ...

Angular - Showing validation messages post successful execution of two functions

I have encountered an issue with my form submission process involving two functions. When both functions succeed, I want to display a successful validation message. However, currently the success message is displayed even if the second function fails. How ...

- "Is it possible to extract values from an optional variable?"

Is there a method to access individual variables from the data returned by the reload method? let reloadProps: ReloadProps | undefined; if (useClientSide() === true) { reloadProps = reload(props.eventId); } const { isTiketAdmin, jwt, user ...

What is the reason behind Jest v24 mocking classes that have a need for private methods

Currently, I am facing a challenge in creating mock implementations of my Typescript classes using Jest v24+. Specifically, I am trying to create a mock class that will be injected into a constructor and mock the functions to return specific responses. My ...

Encountering an error with the Angular 2 SimpleChanges Object during the initial npm start process

Within my Angular 2 application, there exists a component that holds an array of objects and passes the selected object to its immediate child component for displaying more detailed data. Utilizing the "SimpleChanges" functionality in the child component a ...

Using Typescript to establish a connection between ngModel and an object's property

Let's talk about how we can dynamically bind an input to an undefined property in an object. For example, we have an object named user: let user = {}; How can we bind an input to a property that doesn't exist yet? Like this: <input [(ngMode ...

What are the best ways to maximize a web worker's ability to handle multiple tasks at once

I'm currently working on implementing a Web-Worker to handle its state while also managing multiple asynchronous requests. worker.ts file let a =0; //state of the worker let worker=self as unknown as Worker; worker.onmessage =(e)=>{ console ...

The error message "Declaration file for module 'mime' not found" was issued when trying to pnpm firebase app

Currently, I am in the process of transitioning from yarn to pnpm within my turborepo monorepo setup. However, I have run into an issue while executing lint or build commands: ../../node_modules/.pnpm/@<a href="/cdn-cgi/l/email-protection" class="__cf_e ...

Working with nested arrays in TypeScript and how to push values onto them

I am facing some challenges with nested array behavior in TypeScript. I am looking for a way to define a single type that can handle arrays of unknown depth. Let me illustrate my issue: type PossiblyNested = Array<number> | Array<Array<number& ...

Using a memory cache in development with NextJS does not seem to be effective

When exporting my pages for my simple static blog site, everything runs smoothly and quickly. However, in development mode, the generation of posts is sluggish and I'm looking to implement caching to speed up the process. I have set up a file called p ...

NestJS Resolver Problem: Getting an Undefined Error

Could use a bit of assistance. I'm currently working on a mutation and encountering the following error: ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'entryUser') Here is the resolver code snippet: export class Us ...

Failed deployment of a Node.js and Express app with TypeScript on Vercel due to errors

I'm having trouble deploying a Nodejs, Express.js with Typescript app on Vercel. Every time I try, I get an error message saying "404: NOT_FOUND". My index.ts file is located inside my src folder. Can anyone guide me on the correct way to deploy this? ...

Discover the power of TypeScript's dynamic type inference in functions

Below is a function that selects a random item from an array: const randomFromArray = (array: unknown[]) => { return array[randomNumberFromRange(0, array.length - 1)]; }; My query pertains to dynamically typing this input instead of resorting to u ...

Experiencing difficulty posting data programmatically, but having success using Swagger

When I try to post data using the following line of code, it does not insert data as expected, even though it works with loopback or swagger. this.http.post(this.Root_url2 + 'busbookings', excelBody) See the complete code below: import { ...

Change validators dynamically according to conditions

Scenario: At the start, there is a single text box named Name1, a date picker called DOB1, and a check box labeled Compare. Both Name1 and DOB1 are mandatory. When the checkbox is clicked, two new form controls are dynamically included, named Name2 and DO ...

Guide on creating a typed object variable in Typescript

In my Typescript code, I have an interface called Employees: export interface Employees { [employeeId: string]: { name: string gender: Gender } } I am trying to declare a variable employees that is of type Employees. Here are the attempts I h ...

What is the best way to bring npm packages into an Angular project?

Is there a way to import a package called cssdom into Angular successfully? For example, I tried importing it like this: import * as CssDom from "cssdom"; However, I encountered the following error: https://i.sstatic.net/LzZwQ.png When attemp ...

"Receiving an error message stating 'Was expecting 1 parameter, received 2' while trying to pass a useState function in TypeScript

I am encountering an issue with a component where I pass a useState setter to a utility function: export interface IData { editable: string[]; favourited: string[]; } const [data, setData] = useState<IData | undefined>(undefined) useEffect(() = ...

Generate a dynamic interface using properties and options provided in a JavaScript object

Can Typescript support the following scenario: I have a structure where keys represent properties and values are arrays of options for those properties: const options = { foo: [fooOption1, fooOption2, ...], bar: [barOption1, barOption2, ...], ... } ...