Branded types add type-level tags to distinguish structurally identical types, preventing accidental misuse. Here's how to implement them.
Basic Branded Type
Validated Branded Types
Numeric Branded Types
ID Types
Opaque Types
Path Types
Sanitized Strings
Combining Brands
Generic Brand Utilities
Best Practices
Design:
✓ Use for domain primitives
✓ Create validation functions
✓ Provide type guards
✓ Document constraints
Naming:
✓ Clear, descriptive names
✓ Match domain language
✓ Indicate constraints
✓ Use consistent patterns
Validation:
✓ Validate at boundaries
✓ Throw descriptive errors
✓ Provide unsafe escape hatch
✓ Use type guards for optional
Avoid:
✗ Over-branding everything
✗ Complex nested brands
✗ Skipping validation
✗ Runtime type checking
Conclusion
Branded types prevent mixing up structurally identical types like different ID types or validated strings. Use them for domain primitives that have semantic meaning, create validation functions that return branded types, and combine with type guards for flexible usage. They provide compile-time safety without runtime overhead.