Dynamically loading class in Typescript(Reflection in TS)

Amit Dhawan
2 min readJun 7, 2021

--

Photo by Max Duzij on Unsplash

At times, it is required to load the class at execution time where the type of class is not known. In Typescript, we can take advantage of Compositionwhere in we can tell the class type based on the public interface declared. Let’s dig into what is meant by the public interface and how we can take advantage of composition.

Let’s say there is a class called Cat and Dog which implements the Animal interface. Interfaces are public contracts that are composed of functions and properties and can be implemented by any class.

Below are the relevant classes:-

Animal.ts is an interface that is composed of functions. These functions are public and can be implemented by classes as and when required. ?in front of barkand meow reflects it is an optional function to be implemented. moveand getBreedare by default required functions.

cat.ts and dog.ts are respective classes that implement the Animal interface in other words both classes are composed of some functions based exposed by a public interface

  • getAnimal returns a Animal class constructor type new (breed: string) => Animal.
  • We instantiate the Animal type with respective breed argument at line 17.
  • cat and dog are objects of type Animal as implement the Animal interface and both have there own move method implementation.

Full source code here.

Summary

  1. Composition is an execution time feature. Typescript static checking checks that both cat and dog follow the Animal interface and implement the required methods of the interface.
  2. At execution time, when objects are allocated based on animalType class constructor.
  3. Composition pattern along with dynamic class loading can be a very useful tool in large code base software where adding features is made easier as you just need to create a new class say rat and implement the required methods.

If this post was helpful, please click the clap 👏 button below a few times to show your support! ⬇⬇

--

--