Dynamically loading class in Typescript(Reflection in TS)
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
meowreflects it is an optional function to be implemented.
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
getAnimalreturns a Animal class constructor type
new (breed: string) => Animal.
- We instantiate the Animal type with respective breed argument at line 17.
dogare objects of type Animal as implement the Animal interface and both have there own move method implementation.
Full source code here.
- Composition is an execution time feature. Typescript static checking checks that both
dogfollow the Animal interface and implement the required methods of the interface.
- At execution time, when objects are allocated based on
- 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
ratand implement the required methods.
If this post was helpful, please click the clap 👏 button below a few times to show your support! ⬇⬇