🏅

TypeScript Branded Types

Verified

by Community

Shows how to implement branded types in TypeScript to prevent mixing structurally identical but semantically different types. Covers the brand pattern, validation functions, and use cases like user IDs, currencies, and units.

typescriptbranded-typesnominaltype-safetyvalidation

TypeScript Branded Types

Create nominal types in TypeScript's structural type system using the branding pattern.

Usage

Describe types that should be distinct despite having the same structure for branded type solutions.

Examples

  • "Prevent mixing UserId and PostId even though both are strings"
  • "Create a validated email type that can't be used with raw strings"
  • "How do I brand number types for different currencies?"

Guidelines

  • Explain why structural typing allows accidental type mixing
  • Show the brand/tag pattern with unique symbols
  • Include validation functions that return branded types
  • Cover integration with Zod or io-ts for runtime validation
  • Explain the performance cost (zero) and maintenance trade-offs