10

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?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

3 Answers3

8

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

Aleksey L.
  • 35,047
  • 10
  • 74
  • 84
5

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • 1
    yes the interface is a better choice because it can be implemented by multiple classes and you are not passing any concrete class as argument – Niladri Nov 25 '17 at 08:45
  • If you can add an answer explaining that in full, I will upvote – Alexander Mills Nov 25 '17 at 08:47
  • Classes must have an interface to describe the members there are static, which is the case of the constructor, and an interface for the intances members. You will find the full explanation if you look for _**Difference between the static and instance sides of classes**_ in https://www.typescriptlang.org/docs/handbook/interfaces.html –  Nov 25 '17 at 09:32
0

The following way worked for me.

VarName: typeof ClassName;

Where, typeof is the Javascript keyword.