TypeScript Course
TypeScript
/
Intermediate

Factory Pattern (TS)

Definition

A pattern that provides an interface for creating objects in a superclass, but allows subclasses or logic gates to alter the type of objects that will be created.

Explain Like I'm New

A Factory is an automated vending machine. You don't need to know how the soda is made. You just press the 'Coke' button, and a Coke comes out. The Factory function abstracts away the messy `new` keywords and complex setup logic.

Real World Example

Building an API service factory. You call `ApiServiceFactory.create('user')` and it returns an Axios instance fully pre-configured with the User API base URL and specific Auth headers.

Common Use Cases

  • •Complex object initialization
  • •Decoupling implementation from usage

Interactive Example

Loading Code Playground...

Interview Questions

basic

  • Why use a Factory instead of just exporting multiple classes?

intermediate

  • How do you type the return value of a Factory?

advanced

  • What is an Abstract Factory in TypeScript?

Flash Cards

Question

How do you type the return value?

Click to reveal answer
Answer

You define a common `Interface` (e.g., `interface Button { render(): void }`). Both `MacButton` and `WindowsButton` implement that interface. The Factory's return type is explicitly typed as `Button`, hiding the specific class from the consumer.