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

When Opaque Types Add Value

Recognize scenarios where opaque types prevent bugs versus when they add unnecessary complexity.

When Opaque Types Add Value

You'll learn when opaque types prevent real bugs versus when they create unnecessary ceremony without meaningful safety gains.

The Value Judgment

Opaque types aren't free. They require boilerplate: branded declarations, smart constructors, extraction functions, and careful maintenance. The question isn't "can I make this opaque?" but "will making this opaque prevent bugs that justify the complexity?"

Opaque Types Add Value When...

1. Confusion Has Real Consequences

When swapping two values causes silent, dangerous failures:

type UserId = string & { readonly __brand: "UserId" };
type ProductId = string & { readonly __brand: "ProductId" };

// Bad things happen if these get mixed up:
// - Wrong database queries
// - Privacy violations  
// - Authorization bypasses
function deleteUser(userId: UserId) { /* ... */ }

Without the brand, calling deleteUser(productId) compiles fine but corrupts data.

2. Invariants Must Be Maintained

When values have validation rules that must never be violated:

type PositiveNumber = number & { readonly __brand: "Positive" };

function createPositive(n: number): PositiveNumber | null {
  return n > 0 ? (n as PositiveNumber) : null;
}

// Everywhere else: if you have PositiveNumber, it's valid
function calculateRate(amount: PositiveNumber) {
  // No defensive checks needed!
}

The type guarantees the invariant. Regular number forces defensive programming everywhere.

3. Domain Concepts Are Non-Interchangeable

When your business logic treats similar shapes completely differently:

type USD = number & { readonly __brand: "USD" };
type EUR = number & { readonly __brand: "EUR" };

function charge(amount: USD) { /* ... */ }

// Prevents accidental currency mixing that causes financial errors

Opaque Types Add Complexity When...

1. The Types Have No Semantic Difference

// Overkill:
type FirstName = string & { readonly __brand: "FirstName" };
type LastName = string & { readonly __brand: "LastName" };

// These are just labels. Swapping them is annoying, not dangerous.

If mixing them up is just aesthetically wrong but functionally harmless, regular types suffice.

2. The Values Convert Freely

When you're constantly converting between representations:

type Meters = number & { readonly __brand: "Meters" };
type Feet = number & { readonly __brand: "Feet" };

// If your code constantly converts between these,
// the branding creates extraction/construction noise
// without preventing real bugs

3. Single Use Context

When a value exists in one small context and confusion is impossible:

function processOrder(orderId: string) {
  // Only used here, never passed around
  const items = fetchItems(orderId);
  // ...
}

// Branding orderId adds no value

The Decision Framework

Ask yourself:

  • Has this confusion caused bugs before? Historical evidence matters.
  • Is the invariant complex or expensive to validate? If validation is cheap, runtime checks may be better.
  • Will the branded type spread through the codebase? More spread = more value from compile-time safety.
  • Can I write a clear smart constructor? If validation logic is murky, opaque types may hide problems rather than solve them.

Key Takeaway: Use opaque types when mixing up values would cause silent data corruption, security issues, or business logic errors—not just because values happen to be the same primitive type. The bug prevention must justify the ergonomic cost.