Reputation: 99960
so I have a function which accepts different constructors, like so:
export class SomeSuperClass {
...
}
export class A extends SomeSuperClass {
...
}
export class B extends SomeSuperClass {
...
}
const foo = function(Clazz: SomeSuperClass){
const v = new Clazz();
}
foo(A); // pass the class itself
foo(B); // pass the class itself
the problem is that SomeSuperClass
means that Clazz
will be an instance of SomeSuperClass
, but not SomeSuperClass
itself.
I tried something stupid like this (which obviously doesn't work):
const foo = function(Clazz: SomeSuperClass.constructor){
const v = new Clazz();
}
what's the right way to do this?
Upvotes: 11
Views: 12789
Reputation: 899
The following way worked for me.
VarName: typeof ClassName;
Where, typeof is the Javascript keyword.
Upvotes: 0
Reputation: 99960
After looking at this answer, it looks like the only way to do this is like so:
interface ISomeSuperClass {
new (): SomeSuperClass;
}
where foo would then become:
const foo = function(Clazz: ISomeSuperClass){
const v = new Clazz();
}
This seems kind of weird, but it compiles.
Upvotes: 5
Reputation: 37918
As you mentioned, what you are looking to is how to describe class constructor and not the instance. It can be achieved by:
const foo = function(ctor: new() => SomeSuperClass) {
...
}
Or alternatively (same result in this case):
const foo = function(ctor: typeof SomeSuperClass) {
...
}
This also requires A
and B
to have parameterless constructors
Upvotes: 9