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

Smart Constructor Functions

Build constructor functions that validate input and return branded opaque types safely.

Smart Constructor Functions

What you'll learn: How to build functions that validate input and safely return branded opaque types, preventing invalid data from entering your system.


The Core Idea

A smart constructor is a function that combines runtime validation with compile-time type branding. Unlike regular constructors or factory functions that blindly accept input, smart constructors verify that data meets your requirements before returning a branded type.

Think of it like a security checkpoint at an airport. Regular functions are like unlocked doors—anyone can walk through. Smart constructors are like TSA checkpoints that verify credentials before granting access to the secure area (your branded type).

How It Works

You create a function that:

  1. Takes primitive input (like string or number)
  2. Validates it at runtime
  3. Only returns the branded type if validation passes
  4. Returns null, undefined, or throws an error if validation fails

The key: the only way to obtain the branded type is through the smart constructor. You never expose the brand symbol publicly, making it impossible to create invalid values.

Basic Example

// Brand symbol (not exported!)
declare const EmailBrand: unique symbol;
type Email = string & { readonly [EmailBrand]: true };

// Smart constructor (exported)
export function createEmail(input: string): Email | null {
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (regex.test(input)) {
    return input as Email;
  }
  return null;
}

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

Because the brand symbol is private, users cannot bypass validation with type assertions.

Why This Matters

Smart constructors give you guaranteed invariants. If a function receives an Email type, you know it's been validated—no defensive checks needed inside that function. The type system enforces that all values passed validation at construction time.

Key Takeaway: Smart constructors combine runtime validation with branded types to create a compile-time guarantee that values are valid, making illegal states unrepresentable in your codebase.