Branded type confusion: intersection with phantom property
Quick summary
You used a branded type (string & { __brand: 'X' }) but did not properly construct the brand — the phantom property does not exist at runtime.
Why this happens
A branded type is created with a type assertion without a constructor function that validates the value
The phantom brand property is checked at compile time but does not exist at runtime, causing confusion
Two branded types with the same underlying type are mixed up because the brand is not enforced at runtime
Minimal example
type UserId = string & { __brand: 'UserId' };
const id = 'not-a-uuid' as UserId; // no validation!
function getUser(id: UserId) { /* ... */ }
getUser(id); // accepts invalid IDtype UserId = string & { __brand: 'UserId' };
function makeUserId(s: string): UserId {
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(s)) {
throw new Error('Invalid UUID');
}
return s as UserId;
}
const id = makeUserId('550e8400-e29b-41d4-a716-446655440000'); // validatedThe factory function validates the string is a proper UUID before casting to the branded type, ensuring runtime safety alongside compile-time type safety.
How to diagnose
Check if the branded value was created through a proper constructor function or just a type assertion
Use a runtime check (e.g., UUID regex) in the constructor to validate the value matches the brand
Log the branded value at runtime to confirm it is just the underlying primitive with no phantom property
How to fix
Create a factory function that validates the value and casts to the branded type: function makeUserId(s: string): UserId
Add runtime validation in the factory function to ensure the value meets the brand's requirements
Use a class-based branded type with a private constructor to prevent direct instantiation without validation
How to prevent
Always create branded types through validated factory functions, never through raw type assertions
Add runtime validation in the factory to ensure the value matches the brand's semantic requirements
Related Resources
Related Glossary
Related Lessons
- Advanced Types
Learn about branded types.