Documenting Intent with Branded Types
What you'll learn: How to use branded types to make domain constraints and business rules visible and enforceable directly in the type system.
The Documentation Problem
You've learned how types can act as self-documenting code, but consider this common scenario:
function transferMoney(fromId: string, toId: string, amount: number) {
// implementation
}
This signature tells you structure (strings and numbers), but nothing about intent. What kind of strings are these? Can any number be an amount? The types don't communicate the business rules: account IDs must be validated, amounts must be positive, etc.
Branded Types as Documentation
Branded types encode domain rules directly into the type system, making invalid states unrepresentable:
type AccountId = string & { readonly __brand: 'AccountId' };
type PositiveAmount = number & { readonly __brand: 'PositiveAmount' };
function transferMoney(
fromId: AccountId,
toId: AccountId,
amount: PositiveAmount
) {
// implementation
}
Now the signature documents that these aren't just any strings or numbers—they carry semantic meaning and have passed validation.
Enforcing Construction
The brand prevents accidental usage:
// ❌ This won't compile - plain strings aren't AccountIds
transferMoney('abc', 'def', 100);
// ✅ Must construct through validation
function createAccountId(raw: string): AccountId {
if (!/^ACC-\d{6}$/.test(raw)) {
throw new Error('Invalid account ID format');
}
return raw as AccountId;
}
const validId = createAccountId('ACC-123456');
The type system now documents and enforces that only validated IDs can be used. Anyone reading the code immediately understands: "This function requires validated account identifiers, not arbitrary strings."
Business Rules as Types
This pattern shines when encoding domain constraints:
type EmailAddress = string & { readonly __brand: 'EmailAddress' };
type NonEmptyString = string & { readonly __brand: 'NonEmptyString' };
type Percentage = number & { readonly __brand: 'Percentage' }; // 0-100
Each branded type is a living piece of documentation that communicates validation requirements, acceptable ranges, and semantic meaning—all enforced at compile time.
Key Takeaway: Branded types transform your type signatures from technical contracts into domain-level documentation, making business rules visible and impossible to bypass accidentally.