Flavoring vs Full Branding
What you'll learn: How to use lighter "flavoring" techniques that add type hints without fully blocking structural compatibility, and when to prefer them over strict branding.
The Spectrum of Nominal Typing
You've seen how full branding creates completely incompatible types—even if two branded types have identical structure, TypeScript treats them as fundamentally different. But sometimes that's overkill.
Flavoring sits on the lighter end of the spectrum. It adds a hint of nominal typing—enough to catch obvious mistakes—while still allowing structural compatibility when needed.
Full Branding: Maximum Safety, Zero Flexibility
type UserId = string & { readonly __brand: 'UserId' };
type ProductId = string & { readonly __brand: 'ProductId' };
declare const userId: UserId;
declare const productId: ProductId;
// ❌ Completely blocked
const test: UserId = productId;
With full branding, there's no escape hatch. UserId and ProductId are utterly incompatible, even though both are just strings underneath.
Flavoring: Hints Without Walls
type UserId = string & { readonly __flavor?: 'UserId' };
type ProductId = string & { readonly __flavor?: 'ProductId' };
declare const userId: UserId;
declare const productId: ProductId;
// ❌ Still caught in obvious direct assignments
const test: UserId = productId;
// ✅ But structural compatibility works
function acceptString(s: string) {}
acceptString(userId); // Works fine
Notice the optional ? marker. This is the key difference. The flavor property is optional, so:
- Direct mismatches are caught:
UserIdcan't directly becomeProductId - But structural compatibility remains: Both are still compatible with plain
string
When Flavoring Shines
Use flavoring when you want:
- Protection within your domain (catching
userId/productIdswaps) - But compatibility with utilities (passing to
JSON.stringify,.length, string methods) - Less ceremony in smart constructors (the flavor doesn't need explicit assignment)
type Meters = number & { readonly __flavor?: 'Meters' };
type Seconds = number & { readonly __flavor?: 'Seconds' };
function calculateSpeed(distance: Meters, time: Seconds): number {
return distance / time; // ✅ Works—both are numbers underneath
}
declare const meters: Meters;
declare const seconds: Seconds;
// ❌ Caught
const wrong: Meters = seconds;
The flavor prevents direct confusion, but doesn't block mathematical operations or library interop.
The Trade-off
- Full branding: Maximum safety, requires smart constructors everywhere, can be verbose
- Flavoring: Catches common mistakes, plays nicely with existing APIs, slightly weaker guarantees
Think of flavoring as a guardrail, not a wall.
Key Takeaway: Flavoring uses optional brand properties to hint at intent and catch direct type confusion while preserving structural compatibility with base types—choose it when you want safety without the rigidity of full nominal branding.