Sub topic 1
Why TypeScript lets you mix up IDs: structural typing
Prerequisites
You should know basic TypeScript type aliases, functions, generics, and intersection types. You should also understand that TypeScript types are checked at compile time, while JavaScript values run at runtime.
Why TypeScript uses structural typing
TypeScript uses structural typing. A value is compatible with a type when it has the required structure, regardless of the type alias name.
This is useful for flexible code, but it cannot distinguish two strings with different domain meanings:
type UserId = string;
type OrderId = string;
function loadOrder(id: OrderId): void {
console.log("loading", id);
}
const userId: UserId = "u_123";
loadOrder(userId); // Allowed: both aliases are stringUserId and OrderId describe the same structure. Their names do not create separate types.
flowchart TD
A[UserId] --> C[string]
B[OrderId] --> C
C --> D[Assignable to either parameter]The problem with plain string and number aliases
This issue is sometimes called primitive obsession: important domain concepts are represented only by primitive values such as string or number.
The compiler cannot detect these mistakes:
| Domain value | Runtime representation | Can plain aliases distinguish it? |
|---|---|---|
| User ID | string | No |
| Order ID | string | No |
| Meters | number | No |
A function may receive a valid string but the wrong kind of identifier. The program then fails later, far from the original mistake.
Your first branded type
A branded type intersects a primitive with an object containing a distinguishing literal property:
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
function loadOrder(id: OrderId): void {
console.log("loading", id);
}
const userId = "u_123" as UserId;
const orderId = "o_456" as OrderId;
loadOrder(orderId);
loadOrder(userId); // Error: UserId is not assignable to OrderIdThe brand has no runtime value. It exists only during type checking. The assertion creates no validation, so use assertions only after validating data.
A reusable `Brand<T, B>` helper
A generic helper avoids repeating the intersection. A unique symbol keeps the brand key private from ordinary object properties.
declare const brand: unique symbol;
type Brand<T, B extends string> = T & {
readonly [brand]: B;
};
type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;The first type argument is the underlying value. The second identifies its meaning.
Exercise
Why can a UserId alias of string be passed to a function expecting OrderId?
Show answer
Structural typing compares their underlying structure, and both aliases are just string.