What are branded types in TypeScript
· Category: TypeScript
Short answer
Branded types use an intersection with a unique literal or symbol property to create nominally distinct types that share the same underlying structure.
How it works
Because TypeScript uses structural typing, two interfaces with the same shape are interchangeable. Branding adds a fictional property that exists only at compile time, making the types incompatible despite identical runtime values.
Example
type UserId = string & { readonly brand: unique symbol };
type OrderId = string & { readonly brand: unique symbol };
function createUserId(id: string): UserId { return id as UserId; }
Why it matters
Branding prevents bugs where semantically different string or number IDs are mixed up. It is especially useful for database keys, currency amounts, and unit conversions.