Sub topic 3
Your First Branded Type
Assume you know TypeScript type aliases, functions, generics, and intersection types. Also assume you understand that TypeScript checks types at compile time, while JavaScript values exist at runtime.
Why aliases are not enough
TypeScript uses structural typing. A value is assignable when it has the required structure. Primitive values have very little structure, so aliases of the same primitive remain interchangeable:
type UserId = string;
type OrderId = string;
function loadOrder(id: OrderId): void {
console.log("loading order", id);
}
const userId: UserId = "u_123";
loadOrder(userId); // AllowedThe aliases document meaning for humans, but they do not create distinct types. TypeScript sees both UserId and OrderId as string.
A branded type adds a property that exists only in the type system. The property gives TypeScript a shape that distinguishes one meaning from another.
Intersecting a primitive with a tag
An intersection type combines multiple requirements. The & below means that a value must be both a string and an object with the specified property:
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
function loadOrder(id: OrderId): void {
console.log("loading order", id);
}
const userId = "u_123" as UserId;
const orderId = "o_456" as OrderId;
loadOrder(orderId);
loadOrder(userId); // ErrorThe two brands have different string literal types. Therefore, UserId is not assignable to OrderId.
The readonly modifier prevents code from changing the tag through a typed property. The property is not added to the actual string at runtime. It is a compile-time marker.
Producing branded values
A type assertion can tell the compiler that a value has a brand:
type UserId = string & { readonly __brand: "UserId" };
function loadUser(id: UserId): void {
console.log("loading user", id);
}
const id = "u_123" as UserId;
loadUser(id);This assertion does not check the string. Any string can be asserted as UserId, including an empty string or a value intended for another domain. Use assertions only at a controlled boundary, such as a constructor that validates its input.
type UserId = string & { readonly __brand: "UserId" };
function parseUserId(value: string): UserId {
if (!/^u_[a-zA-Z0-9]+$/.test(value)) {
throw new Error(`Invalid user ID: ${value}`);
}
return value as UserId;
}
function loadUser(id: UserId): void {
console.log("loading user", id);
}
const id = parseUserId("u_123");
loadUser(id);The parseUserId function is a smart constructor. It checks the runtime value, then returns the corresponding branded type. Callers do not need to repeat the assertion.
Exercise
Exercise
Why does type UserId = string fail to prevent passing a user ID to a function that expects an order ID, while string & { readonly __brand: "UserId" } succeeds?
Show answer
The alias is still structurally identical to string, so both aliases are interchangeable. The intersection adds a distinct literal tag, giving TypeScript different structures for the two domain types.