Course contentsShow
← TypeScript
Lesson 1352 of 1,79631. Type-Driven DesignFree lesson

Smart Constructor Pattern

Building factory functions that validate input and return branded types, ensuring invariants at creation time.

Smart Constructor Pattern

What you'll learn: How to build factory functions that validate input and return branded types, ensuring domain rules are never violated.


The Core Idea

You've learned that branded types prevent accidental substitution of structurally identical values (like different ID types). But how do you create branded values safely?

The Smart Constructor Pattern solves this: you write a factory function that:

  1. Validates all input according to your domain rules
  2. Returns a branded type only if validation succeeds
  3. Never exports the raw type constructor

This makes invalid states impossible to construct, not just hard to construct.


Why This Matters

Imagine an email type. You could brand it, but what stops someone from writing "invalid" as Email? Nothing. Smart constructors close this loophole by making the factory function the only way to create branded values.


Basic Pattern Structure

// Brand the type
type Email = string & { readonly __brand: 'Email' };

// Smart constructor (the ONLY way to create Email)
function createEmail(input: string): Email | null {
  if (!input.includes('@')) {
    return null; // Validation failed
  }
  return input as Email; // Safe cast after validation
}

// Usage
const valid = createEmail('user@example.com'); // Email | null
const invalid = createEmail('not-an-email'); // null

// This is now impossible without the constructor:
// const bad: Email = 'anything'; // Type error - can't assign string to Email

The assertion as Email is now justified because we've proven the invariant holds.


Result Type Pattern

Instead of returning null, many smart constructors return a discriminated union for richer error handling:

type Success<T> = { success: true; value: T };
type Failure = { success: false; error: string };
type Result<T> = Success<T> | Failure;

function createEmail(input: string): Result<Email> {
  if (!input.includes('@')) {
    return { success: false, error: 'Email must contain @' };
  }
  return { success: true, value: input as Email };
}

Enforcing the Pattern

To prevent bypassing the constructor:

  • Never export the brand or raw type constructor
  • Only export the branded type and the smart constructor function
  • Consider using readonly on the brand to prevent mutation

Key Takeaway:
Smart constructors combine validation logic with branded types to guarantee invariants at creation time—once you have a branded value, you know it's valid, making impossible states truly impossible to represent.