Branded Type
In one line
Branded types add a phantom field to distinguish types that have the same structure — preventing UserId/UserEmail mixups.
In simple words
Branded types (also called nominal typing simulation) add a unique phantom property to a type, making it distinct from other types with the same underlying structure.
For example, UserId and OrderId are both strings, but you don't want to pass a UserId where an OrderId is expected. Branding makes them incompatible:
type UserId = string & { readonly __brand: "UserId" }
The __brand property doesn't exist at runtime — it's purely a type-level marker. This catches a whole class of bugs (passing wrong IDs) at compile time.
To create a branded value, you use a constructor function that asserts the brand.
Example
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
// Constructor functions
function userId(s: string): UserId { return s as UserId; }
function orderId(s: string): OrderId { return s as OrderId; }
function getUser(id: UserId) { /* ... */ }
const uid = userId("user-123");
const oid = orderId("order-456");
getUser(uid); // OK
// getUser(oid); // Error! OrderId is not UserId
// getUser("raw-string"); // Error! string is not UserIdThe __brand phantom property makes UserId and OrderId incompatible at compile time, even though they're both strings at runtime.
Common confusions
Confused with: type alias
The difference: A type alias (type UserId = string) creates a new name but UserId and string are interchangeable — no type safety. A branded type (type UserId = string & { __brand: 'UserId' }) makes them incompatible — you can't pass a plain string where UserId is expected.
Related terms
Related Resources
Related Lessons
- TypeScript Advanced Types
Branded types.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.