Factory Pattern In TypeScript Using Type Map
A practical example of implementing a factory pattern that takes advantage of the TypeScript Typing System
Factory pattern is one of the most common creation patterns. It loosely connects the application by hiding the implementation details from the client code using the interface. It leaves the creation of object instances to the factory implementation.
This article aims to show how to improve the factory “creator” with a TypeScript type map.
Users Factory Implementation
We’ll be using a typical example of a factory that creates different types of users: Manager and Developer, for the sake of simplicity. You can imagine there will be many more types in a real project.
Firstly, let’s define our Manager and Developer classes.
In the above code, we define an IStaff
interface, so that both Manager and Developer classes implement it. It’s essential for the Factory pattern to work, so the client code doesn’t need to know a particular class, only the interface.