Back to Blog
TypeScriptBranded TypesType SafetyDomain

TypeScript Branded Types Guide

Master TypeScript branded types for type-safe identifiers and domain modeling.

B
Bootspring Team
Engineering
January 7, 2019
6 min read

Branded types add type-level tags to distinguish structurally identical types, preventing accidental misuse. Here's how to implement them.

Basic Branded Type

Loading code block...

Validated Branded Types

Loading code block...

Numeric Branded Types

Loading code block...

ID Types

Loading code block...

Opaque Types

Loading code block...

Path Types

Loading code block...

Sanitized Strings

Loading code block...

Combining Brands

Loading code block...

Generic Brand Utilities

Loading code block...

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.

Share this article

Help spread the word about Bootspring

Related articles