In an attempt to replicate a project issue, I crafted this piece of TypeScript code. The scenario involves having a base class (referred to as "Foo") and multiple other classes that extend from it. The goal of the "instanciateFoos" function is to create an instance of a class similar to Foo (in this case, "Bar") and return it with the correct type. Dealing with lengthy class names poses a challenge, as calling the function often requires repeating the class name. As a workaround, I find myself always needing to cast the returned object to the class initially passed into the function in order for TypeScript to recognize it as an instance of that class. Perhaps there is a solution to this dilemma using generics or a similar approach.
class Foo
{
constructor() { }
}
class Bar extends Foo
{
talk()
{
console.log("Bar");
}
}
function instanciateFoos(fooLikeClass: typeof Foo)
{
return new fooLikeClass();
}
let myBar = instanciateFoos(Bar);
myBar.talk();
// Error: Property 'talk' does not exist on type 'Foo'.ts(2339)
let myBar2 = <Bar>initiateFoos(Bar);
myBar2.talk();
// works