I want to create an instance of T in a generic class in Typescript.
The following code is something I thought would work, but unfortunately it does not.
type Constructor<T> = { new(...args: any[]): T };
class Bar { }
class Foo<T extends Constructor<T>> {
constructor( /* some parameters here, but NOT a type creator! */ ) {}
create(): T {
return new T();
}
}
const bar: Bar = new Foo<Bar>().create();
Well there are some other questions/answers here on SO, but all use some kind of type creator that needs to be passed to the generic class/function, like so:
function create<T>(creator: new() => T): T {
return new creator();
}
const bar: Bar = create<Bar>(Bar);
But my ctor needs to not have something like that. The create function should always stay parameter-less. Is there a way to make this work?
createbe parameterless? Can you pass thecreatorparameter instead to the constructor of theFooclass? You have to pass the constructor of your classTintoFoosomehow, one way or another, or this won't work. Try considering how you would do it in plain JS, then add types afterward.