Alexander Mills
Alexander Mills

Reputation: 99960

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?

Upvotes: 11

Views: 12789

Answers (3)

Manjunath Hadimani
Manjunath Hadimani

Reputation: 899

The following way worked for me.

VarName: typeof ClassName;

Where, typeof is the Javascript keyword.

Upvotes: 0

Alexander Mills
Alexander Mills

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

Aleksey L.
Aleksey L.

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

Related Questions