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

Opaque Type Pattern

Using a module boundary to hide the structure of a type entirely, exposing only constructor and accessor functions.

What You'll Learn

You'll learn how to completely hide the internal structure of a type behind a module boundary, exposing only controlled constructor and accessor functions to ensure safe, validated usage.


The Core Idea

The Opaque Type Pattern takes branding to its ultimate conclusion: instead of just marking a type with a brand, you hide the entire type definition inside a module and only export functions that create and work with it.

Unlike branding (where the structure is visible but incompatible), opaque types make the structure completely invisible to outside code. This enforces that values can only be created through your controlled constructor functions, which can validate and guarantee invariants.


How It Works

Create a branded type inside a module, but don't export the type itself—only export:

  1. Constructor functions that validate and return the opaque type
  2. Accessor/utility functions that work with the opaque type

The type itself remains private to the module.

// email.ts - The Module Boundary
declare const EmailBrand: unique symbol;

// The type is NOT exported - it's opaque to the outside world
type Email = string & { readonly [EmailBrand]: true };

// Export only the constructor
export function createEmail(value: string): Email | null {
  if (!value.includes('@') || value.length < 3) {
    return null;
  }
  return value as Email;
}

// Export only accessors
export function emailToString(email: Email): string {
  return email;
}

export function getDomain(email: Email): string {
  return email.split('@')[1];
}

// Type alias exported for annotations, but structure hidden
export type { Email };
// main.ts - Using the Opaque Type
import { createEmail, getDomain, type Email } from './email';

const email = createEmail("user@example.com");

if (email) {
  console.log(getDomain(email)); // "example.com"
}

// ✅ Can annotate with the type
let userEmail: Email | null = null;

// ❌ Cannot construct directly - no access to brand
// const fake: Email = "hacker@evil.com" as Email; // Brand not accessible

// ❌ Cannot bypass validation
// userEmail = "invalid" as Email; // Brand symbol not in scope

The module boundary enforces that only validated values can become Email types, because the brand symbol itself is private to the module.


Why This Matters

Opaque types guarantee total encapsulation: users cannot forge, construct, or manipulate the type without going through your controlled API. This is stronger than branding alone, where the structure is technically visible.

Key Takeaway: The Opaque Type Pattern hides a type's structure entirely within a module, exposing only validated constructors and accessors—guaranteeing invariants through complete encapsulation.