One of the challenges I'm facing involves dynamically creating subclasses and ensuring that the factory function is aware of the subclass's return type.
While I can currently achieve this using a cast, I am exploring options to infer the return type without requiring such explicit casting.
class Greetings {
x = 5;
}
class Greetings2 extends Greetings {
y = 10;
}
class Greetings3 extends Greetings {
z = 15;
}
function generate<T extends typeof Greetings>(constructor: T): InstanceType<T> {
// Without this cast, the code won't compile successfully
return new constructor() as InstanceType<T>;
}
// This fails due to incorrect constructor type
const g1 = generate(Number);
const g2 = generate(Greetings2);
console.log(g2.y); // no error
const g3 = generate(Greetings3);
console.log(g3.z); // no error