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.