Reputation: 157
I'm using a similar pattern to this:
class MyClass { }
doSomethingWithClass(MyClass) { }
If I were to add typing to my code, using Flow or TS, how would I type this? Wouldn't something like this imply that I'm expecting an instance of MyClass?
doSomethingWithClass(MyClass: MyClass) { }
What I want to do is pass the constructor/class into a factory pattern, but I don't know how to actually type it.
Upvotes: 1
Views: 95
Reputation: 3201
Use the Class<> utility type.
class MyClass { };
function doSomethingWithClass(klass: Class<MyClass>): void {
}
doSomethingWithClass(MyClass)
Upvotes: 0
Reputation: 249536
In order to pass a class constructor to a function you can use a constructor signature:
function doSomethingWithClassGeneric<T>(myClass: new () => T) {
return new myClass()
}
doSomethingWithClassGeneric(MyClass);
Above we use a constructor with no arguments but you can potentially require parameters to the constructor to be present.
Or you can also use typeof MyClass
to accept classes derived from MyClass
with a compatible constructor:
class MyClass { }
class MyClassDerived extends MyClass { x!: number }
function doSomethingWithClassGeneric<T>(myClass: typeof MyClass) {
return new myClass()
}
doSomethingWithClassGeneric(MyClass);
doSomethingWithClassGeneric(MyClassDerived);
Upvotes: 4