TIL: Passing class as method’s params on TypeScript

Taufan
2 min readJun 16, 2020

I was experimenting with a factory that build an instance of a class, which is passed as a parameter of the factory method. However, TypeScript kept throwing an error as I type the parameter with an interface.

Messenger interface
Messenger interface

The error thrown was “Type ‘Messenger’ has no construct signatures”.

Failing factory method
The failing factory method

The error is quite literal, the interface is not new-able as it does not specify how to construct the instance. Usually, when a variable is typed as an interface, we expect its value to be an instance that implements that interface.

The solution to this problem is to create a separate interface that defines how the class that implements the interface might be constructed, i.e. new-ed.

Working factory with additional MessengerConstruct interface
The working factory method

The MessengerConstruct interface defines how to construct the instance that implementsMessenger. It does so by defining the new method. Now, TypeScript will not complain about the earlier error anymore.

Another advantage is that now we can dictate how the class should be constructed, to make sure we always pass in a class with the right constructor signature. And in a case where there might be more than one way to construct the class, we can just overload the new definition in the construct interface.

Messenger construct overload
MessengerConstruct with method overload

This post is based on an old SO answer. Constructive feedbacks are welcomed. See you in the next post!

--

--