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

What Opaque Types Are

Learn how opaque types hide implementation details while preserving nominal type distinctions at compile time.

What Opaque Types Are

You'll learn: How opaque types create compile-time distinctions between structurally identical types while hiding their internal representation.


The Core Idea

An opaque type is a type that reveals only its interface—what you can do with it—while completely hiding how it's implemented underneath. Unlike structural typing where two types with identical shapes are interchangeable, opaque types create distinct identities that TypeScript treats as incompatible, even when their runtime representations are identical.

Think of it like sealed envelopes: you might have two envelopes that are physically identical, but one is labeled "Medical Records" and the other "Financial Records." You shouldn't be able to accidentally use one in place of the other, even though they're structurally the same.

How Opaque Types Work

Opaque types build on the brand technique you've already learned. They use an invisible marker (the brand) to create nominal-like behavior in TypeScript's structural type system. The "opaque" part means the implementation details—the actual string, number, or object—remain hidden from the outside world.

The key insight: the brand property is never actually created at runtime. It exists purely at the type level. This means zero runtime overhead while maintaining complete compile-time safety.

Why Hide Implementation Details?

When you make a type opaque, you're enforcing that values can only be created through controlled constructor functions. This prevents:

  • Accidentally creating invalid values by direct assignment
  • Bypassing validation logic
  • Confusing semantically different values that happen to share structure
  • Implementation changes breaking consumer code

The opacity ensures consumers interact with your types through well-defined boundaries, never reaching inside to manipulate the raw data directly.


Key Takeaway: Opaque types combine branding for nominal distinctions with complete encapsulation of implementation, ensuring values can only be created through validated constructors while remaining structurally hidden from direct manipulation.