Branding Primitive Types
What you'll learn: How to create distinct, incompatible types from basic primitives like strings and numbers to prevent accidental misuse in your domain logic.
The Domain-Specific Primitive Problem
You've seen how structural typing lets you substitute types freely. But sometimes you don't want a regular string to be compatible with, say, an Email. Even though both are strings at runtime, they represent different concepts in your domain.
Branding solves this by tagging primitive types with unique compile-time markers. This creates nominal-like behavior in TypeScript's structural world—two branded strings won't accidentally mix even though they're both strings underneath.
Applying Brands to Strings
type Email = string & { readonly __brand: 'Email' };
type Username = string & { readonly __brand: 'Username' };
// These look like strings, but TypeScript treats them as distinct types
declare const email: Email;
declare const username: Username;
// ❌ Error: Type 'Email' is not assignable to type 'Username'
const user: Username = email;
The __brand property never exists at runtime—it's a phantom type. But TypeScript checks it at compile time, preventing substitution.
Numeric Brands for Constraints
type PositiveInt = number & { readonly __brand: 'PositiveInt' };
type Age = number & { readonly __brand: 'Age' };
// Age and PositiveInt are separate types, even though both are numbers
declare const age: Age;
declare const count: PositiveInt;
// ❌ Error: can't assign Age to PositiveInt
const invalid: PositiveInt = age;
This prevents mixing domain concepts like age, count, price, or ID—all numbers, but semantically different.
Smart Constructors Enforce the Brand
You can't just cast any string to Email—you need a validation function that returns the branded type:
type Email = string & { readonly __brand: 'Email' };
function validateEmail(input: string): Email {
if (!input.includes('@')) {
throw new Error('Invalid email');
}
return input as Email; // Safe cast after validation
}
const myEmail = validateEmail('user@example.com'); // Email
const plainString = 'no-at-sign';
// ❌ Error: string is not assignable to Email
const broken: Email = plainString;
The brand is your type-level proof that validation succeeded.
When to Use Branded Primitives
- Identifiers:
UserId,OrderId,ProductIdprevent mixing IDs - Validated data:
Email,PhoneNumber,URLensure format checks - Constrained numbers:
PositiveInt,Percentage,NonZero - Non-empty collections:
NonEmptyString,NonEmptyArray<T>
Key Takeaway: Branding primitive types with intersection markers creates compile-time distinctions between domain concepts that share the same runtime representation, enforcing validation and preventing logical errors through the type system.