← TypeScript

Patterns & principles · 2 of 10 · 15 min read

The Factory pattern

A function that decides what to build — and in TypeScript, one that can return a different type depending on what it was asked for.

  • Design patterns

A factory is a function that creates something, hiding which concrete thing it created. In TypeScript the interesting part is the return type: a factory can be typed so the caller gets exactly the variant they asked for, with no assertion and no narrowing.

The simplest form

interface User {
  readonly id: string;
  readonly name: string;
  readonly createdAt: Date;
  readonly roles: readonly string[];
}

function createUser(name: string, roles: readonly string[] = ["user"]): User {
  return {
    id: crypto.randomUUID(),
    name,
    createdAt: new Date(),
    roles,
  };
}

const user = createUser("Ana");
console.log(user.name, user.roles);

The defaults, the generated id and the timestamp live in one place, and the result is readonly all the way down because nothing needs to mutate it after construction. A constructor can do the same; what it cannot do is return a different type, return a cached instance, or be passed around as a value.

Factory function Constructor
Return type anything, including a union or a conditional the class, always
Can return an existing instance yes no (a new always allocates)
Can be async yes no
Passed as a value yes, it is a function only as typeof C
Chosen at runtime trivially needs a registry of constructors
instanceof works on the result only if it returns a class instance yes
Private state a closure #field

Returning the variant that was asked for

This is what TypeScript adds, and it is worth writing out carefully:

interface Circle { kind: "circle"; radius: number; area(): number }
interface Square { kind: "square"; side: number; area(): number }

interface ShapeMap {
  circle: Circle;
  square: Square;
}

function createShape<K extends keyof ShapeMap>(kind: K, size: number): ShapeMap[K] {
  const shape =
    kind === "circle"
      ? { kind: "circle", radius: size, area: () => Math.PI * size ** 2 }
      : { kind: "square", side: size, area: () => size ** 2 };
  return shape as ShapeMap[K];
}

const circle = createShape("circle", 2);  // Circle — not Circle | Square
console.log(circle.radius, circle.area().toFixed(2));

const square = createShape("square", 2);
console.log(square.side);

circle.radius with no narrowing is the whole point. A factory returning Circle | Square would force every caller to check kind even though they just said which one they wanted.

The as inside is the cost, and it is the usual one: a return type the compiler cannot verify against the body. Keep such a factory small, and let the map be the thing that is reviewed.

An overload set expresses the same thing with per-signature parameters:

interface Circle { kind: "circle"; radius: number }
interface Square { kind: "square"; side: number }

function createShape(kind: "circle", radius: number): Circle;
function createShape(kind: "square", side: number): Square;
function createShape(kind: "circle" | "square", size: number): Circle | Square {
  return kind === "circle" ? { kind, radius: size } : { kind, side: size };
}

console.log(createShape("circle", 2).radius);

Use overloads when the arguments differ between variants, and the generic-plus-map form when only the return type does. The map scales better: adding a shape adds a line to ShapeMap, not two more signatures.

A registry of factories

Where Factory and Strategy meet, and the shape most real code ends up with:

interface Notifier {
  readonly channel: string;
  send(message: string): Promise<void>;
}

type Channel = "email" | "sms" | "push";

const factories: Record<Channel, (config: { target: string }) => Notifier> = {
  email: ({ target }) => ({
    channel: "email",
    async send(message) { console.log(`email to ${target}: ${message}`); },
  }),
  sms: ({ target }) => ({
    channel: "sms",
    async send(message) { console.log(`sms to ${target}: ${message}`); },
  }),
  push: ({ target }) => ({
    channel: "push",
    async send(message) { console.log(`push to ${target}: ${message}`); },
  }),
};

function createNotifier(channel: Channel, target: string): Notifier {
  return factories[channel]({ target });
}

await createNotifier("sms", "+34600000000").send("ready");

Record<Channel, ...> means adding a channel to the union is a compile error until a factory exists for it. The caller depends on Notifier, never on the concrete implementations — which is the dependency-inversion half of what a factory buys.

Validating on the way in

A factory is the natural place for a boundary check, because it is the only way the type gets created:

interface Email { readonly value: string; readonly __brand: "Email" }

function createEmail(value: string): Email {
  const trimmed = value.trim().toLowerCase();
  if (!trimmed.includes("@")) throw new Error(`not an email: ${value}`);
  return { value: trimmed, __brand: "Email" } as Email;
}

function send(to: Email) { return `sending to ${to.value}`; }

console.log(send(createEmail(" ANA@example.com ")));
// send({ value: "nope", __brand: "Email" }); // the brand is not constructible by hand

The branded type and the factory are one idea: a type nobody can produce except through a function that validates. That turns “this string has been checked” from a convention into something the signature states.

Async factories

Constructors cannot be async, which is the most common practical reason to reach for a factory:

interface Database {
  query(sql: string): Promise<unknown[]>;
  close(): Promise<void>;
}

async function createDatabase(url: string): Promise<Database> {
  // await the connection here — a constructor could not
  const connected = await Promise.resolve({ url });
  return {
    async query(sql) { return [connected.url, sql]; },
    async close() { console.log("closed"); },
  };
}

const db = await createDatabase("postgres://localhost");
console.log(await db.query("select 1"));

The alternative — a constructor that starts the work and a separate ready promise — gives every caller an object that is not usable yet, and a type that cannot say so.

Static factory methods

When the factory belongs to the class, a static keeps it close without losing the benefits:

class Temperature {
  private constructor(readonly celsius: number) {}

  static fromCelsius(value: number) { return new Temperature(value); }
  static fromFahrenheit(value: number) { return new Temperature((value - 32) / 1.8); }

  get fahrenheit() { return this.celsius * 1.8 + 32; }
}

// new Temperature(20);  // the constructor is private
console.log(Temperature.fromFahrenheit(68).celsius); // 20

private constructor is the piece that makes this a real pattern rather than a convenience: there is exactly one way to build the type, so the named factories are not optional. Two constructors taking a number would be ambiguous; two named methods are not.

Common mistakes

A factory returning the union

Mistake. function createShape(kind: Kind): Circle | Square. Why it fails. Every caller must narrow a type they already know, usually with an as that defeats the point. What to do instead. A generic parameter indexed into a map, so the return type follows the argument.

any as the escape from a hard return type

Mistake. function create(kind: string): any. Why it fails. The factory becomes a hole: every property access on the result is unchecked, including the misspelled ones. What to do instead. A map plus keyof, or overloads. If the shapes are genuinely unknowable, return unknown and narrow once.

A factory that is only new with extra steps

Mistake. function createUser(name: string) { return new User(name); }. Why it fails. It adds a layer and buys nothing — no defaults, no validation, no choice of implementation, no async. What to do instead. Export the class. Add the factory when there is a decision to hide.

Check yourself

One question from the bank on what you just read. Answering here does not affect your quiz history.

What makes a factory function in TypeScript more useful than a constructor here?

Practise Design patterns →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.