Generic with Construction Functions

This lesson explains how to apply the generic type to a construction function.

Restricting the signature of a constructor

In some scenarios, someone may need to instantiate a generic object from a function.

const obj = funct(TypeIWantToInstantiate, parameter1, parameterx);

The goal is to have a type constraint on the construction of an object type.

It is possible to use the constructed signature in a construction function to dynamically create a new instance of a specific type that requires an exact constructor signature.

A construction function is a function that returns a new object.

A constructor signature is the type and number of the parameters.

For example, a function taking T as a generic argument can require an argument of type {new(): T; } and returns T. An interface with a member of new indicates that the class must have a constructor with the defined parameter. In the following code, line 2 constrains any type passed to have a constructor with a single parameter of type string.

Get hands-on with 1400+ tech skills courses.