Extracting the Underlying Value
What you'll learn: How to safely access the raw primitive value wrapped inside an opaque (branded) type when you actually need it.
The Need for Unwrapping
You've created opaque types to prevent misuse and confusion between conceptually different values (like UserId vs ProductId). But sometimes you do need the actual primitive value—perhaps to serialize to JSON, log for debugging, or pass to a third-party library that doesn't know about your brands.
This is where extraction utilities come in.
Core Pattern: The Unwrap Function
The simplest approach is a dedicated function that strips the brand:
type UserId = string & { readonly __brand: "UserId" };
function unwrapUserId(id: UserId): string {
return id as string;
}
// Usage
declare const userId: UserId;
const rawString = unwrapUserId(userId); // string
This type assertion is safe because at runtime, UserId is just a string—the brand exists only at compile time.
Generic Unwrap Utility
For multiple branded types, create a reusable helper:
type Brand<T, B> = T & { readonly __brand: B };
function unwrap<T, B>(branded: Brand<T, B>): T {
return branded as T;
}
type UserId = Brand<string, "UserId">;
type Age = Brand<number, "Age">;
declare const userId: UserId;
declare const age: Age;
const rawId = unwrap(userId); // string
const rawAge = unwrap(age); // number
Analogy: The Security Envelope
Think of opaque types like security envelopes with special seals. Smart constructors are the sealing process—they validate and mark the envelope. Extraction functions are carefully cutting open the envelope when you need the letter inside. You wouldn't casually rip open every envelope, but sometimes you genuinely need the contents.
When to Extract
Only unwrap when crossing boundaries where the type safety no longer applies:
- Serializing to JSON or databases
- Logging/debugging output
- Interfacing with untyped libraries
- Converting between different type systems
Inside your application logic, keep values in their branded form to preserve safety.
Key Takeaway: Write dedicated unwrap or extract utility functions that safely cast opaque types back to their underlying primitives—but only use them at system boundaries where the brand's protection is no longer meaningful.