I've got a situation where I want to use a generic type in a set of interfaces. My public interface receives the generic type and passes it down to the non-exported private interfaces. In my public interface I want to use the generic type T, but I don't want it to refer to an instance of T. I want it to say that it is T, the class, that can produce instances of T.
Trying this, I get an error:
interface Car<T> {
unit: T;
progress: number;
}
export interface CarFactory<T> {
cars: Car<T>[];
// Type error: 'T' only refers to a type, but is being used as a value here. TS2693
blueprint: typeof T;
}
Using a generator function works. But then I have to pass that down and expose more of the internals of my code, which I want to avoid.
interface CarFactory<T> {
blueprint: (args: any) => T;
}
I can't use T directly, as that causes the compiler to think it should receive an instance of T, not the class. This triggers a TS2740 error. Using T = CarModel and T['constructor'] as the blueprint type works, but only if I patch my class like this:
class CarModel {
public ['constructor']: typeof CarModel;
}
So the question is: How can I use generics like this? Using both instances of T and the actual T? Are a generator function or ['constructor'] with a patched T my only alternatives? Would I need to pass down another generic type U that is something along the lines of U = typeof T?
Tsupposed to be inCar<T>? It's some sort of Car that only works with a given type but I'm not sure if that's what you mean here. Perhaps you don't even need a generic for Car. It seems more logical to me to haveinterface Carwithout a generic and then something likeinterface CarFactory<T extends Car>because the CarFactory will create something that is a Car.constructoras you have inCarModelautomatically, but it is not yet implemented