Design Patterns In TypeScript — Factory

How to create an object without exposing the creation logic

Cesar William Alvarenga
3 min readJun 19, 2021
Photo made with Canva.

The Factory Pattern is one of the core design pattern principles for creating an object. It allows clients to create objects using a common interface. In TypeScript, there are many different ways in which you can use the factory pattern to make your code cleaner and more concise. In this article, we’ll demonstrate how to create a factory pattern using TypeScript Generics.

What is Factory?

The authors of the book Design Patterns: Elements of Reusable Object-Oriented Software define the Factory Pattern as:

Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

In other words, the factory design pattern defines an interface or an abstract class and allows subclasses to decide which object to instantiate. In that way, we are adding polymorphic behavior to the instantiation.

How Does It Work?

The client calls the create function with a subclass from a factory instead of creating objects directly with a concrete class. As a factory corresponds to a single interface variant, all its objects will be compatible.

--

--