TypeScript theorytheory 0/50 · 0%
Types · hard

42. Branded/nominal types

Simulating nominal typing on top of structural types.

TypeScript's structural typing means two differently-named types with the same shape are interchangeable — usually helpful, but risky for values like `UserId` and `OrderId` that are both just `string` underneath. Branding adds a fake, unused property to force distinctness.

ts
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };

function asUserId(id: string): UserId {
  return id as UserId;
}

function getUser(id: UserId) { /* ... */ }

const oid = "order-1" as OrderId;
getUser(oid); // error: OrderId is not assignable to UserId, despite both being strings

The `__brand` field never actually exists at runtime — it's a compile-time-only tag. This pattern is common for modelling distinct identifier types (wallet address vs. transaction hash vs. block hash) that would otherwise all collapse to plain `string` and be silently interchangeable.

Check your understanding

  1. 1. Why would `UserId` and `OrderId`, both `string` underneath, be considered interchangeable by default?

  2. 2. What does the `__brand` property actually exist as at runtime?

  3. 3. What problem does branding solve?