Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare class type with TypeScript (pass class as parameter)

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?

like image 230
Alexander Mills Avatar asked Nov 25 '17 08:11

Alexander Mills


1 Answers

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

like image 128
Aleksey L. Avatar answered Oct 22 '22 23:10

Aleksey L.