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 Composition
where 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 ofbark
andmeow
reflects it is an optional function to be implemented.move
andgetBreed
are 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 typenew (breed: string) => Animal.
- We instantiate the Animal type with respective breed argument at line 17.
cat
anddog
are objects of type Animal as implement the Animal interface and both have there own move method implementation.
Full source code here.
Summary
- Composition is an execution time feature. Typescript static checking checks that both
cat
anddog
follow the Animal interface and implement the required methods of the interface. - At execution time, when objects are allocated based on
animalType
class constructor. - 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! ⬇⬇