pvgdev
pvgdev

Reputation: 157

How to type a Class or Constructor

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

Answers (2)

Dave Meehan
Dave Meehan

Reputation: 3201

Use the Class<> utility type.

class MyClass { };

function doSomethingWithClass(klass: Class<MyClass>): void {
}

doSomethingWithClass(MyClass)

Upvotes: 0

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

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

Related Questions