ReviseAlgo Logo

Advanced TypeScript Patterns

Opaque / Branded Types in Practice

Prevent primitive value mixing using type branding factory helpers.

Last Updated: July 29, 2026 10 min read

Branded (opaque) types attach a unique nominal tag to primitive types (like UserId vs OrderId), preventing developers from accidentally passing an OrderId where a UserId is expected.

1. Introduction & Architecture

2. Deep Dive & Core Concepts

TypeScript uses structural typing, so plain type UserId = string allows passing any string. Adding a unique brand property (__brand) simulates nominal typing for primitive values.

3. Basic Code Example

4. Advanced Production Patterns

5. Interactive Code Playground

console.log("Branded types enforce nominal safety for primitive types.");

6. Common Pitfalls & Edge Cases

Warning: Branded types require explicit constructor/validation helper functions (as UserId) to apply the brand tag.

7. Interview Q&A & Quizzes

Q: What problem do Branded Types solve?

A: They prevent accidental mixing of structurally identical primitive types (e.g., preventing UserId from being passed to an OrderId parameter).

8. Summary Comparison Table

Typing ApproachInterchangeable Primitive AssignmentNominal Safety
Type Alias (type Id = string)YesNo
| Branded Type (Brand) | No | Yes |