Currently in the process of writing a TypeScript class factory, my goal is to have a function output a type as its result. While TypeScript handles types as inputs using generics effectively, I am facing challenges when it comes to dealing with types as outputs.
Although a StackOverflow post on class factories provided some guidance, it did not fully address my concerns. This is the structure being discussed:
function factory(someVar: any) {
return class A {
// Code specific to someVar to create unique instances
}
}
The post suggests utilizing the following approach when working with the output of the factory function:
import factory from "someLocation";
const AClass = factory({foo: "bar"});
type A = InstanceType<typeof AClass>;
interface IData {
someField: A;
}
I am keen on integrating this functionality into my factory function for enhanced reusability and modularity. However, my struggle lies in figuring out how to return a type from a function. When attempting the following approach, TypeScript throws an error:
function factory(someVar: any) {
class AClass {
// Code specific to someVar to create unique instances
}
type A = InstanceType<typeof AClass>;
return A;
}
How can I achieve this? Is there a correct way to handle types as values or variables in TypeScript? If not, what are the reasons behind this limitation? Additionally, how could one go about using this type as a constructor, if feasible?