AI Hints
Home›TypeScript Tutorial›Precise Types
TypeScript · Lesson 89 of 120

Branded Types

Ids that can't mix.

⏱ 2 min read▶ Video at 1:09:40🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

An order ID and a customer ID are both numbers. Mixing them up is an easy, nasty bug. A brand adds an invisible tag to a type, so the two can't be swapped.

Branded Types
From the video: Branded Types
  • Two kinds of ids
  • Easy to mix up
  • Add a brand

Mixed-up ids

Order ID and customer ID are numbers with different brands. Helper functions create them. Cancel order needs an order ID. Passing a customer ID is rejected. Run it.

app.tstypescript
type OrderId = number & { readonly __brand: "OrderId" };
type CustomerId = number & { readonly __brand: "CustomerId" };

const orderId = (n: number) => n as OrderId;
const customerId = (n: number) => n as CustomerId;

function cancelOrder(id: OrderId) { console.log("Cancelling", id); }

cancelOrder(orderId(1042));
cancelOrder(customerId(7));
Output
app.ts line 10: Argument of type 'CustomerId' is not assignable to parameter of type 'OrderId'.
  Type 'CustomerId' is not assignable to type '{ readonly __brand: "OrderId"; }'.
    Types of property '__brand' are incompatible.
      Type '"CustomerId"' is not assignable to type '"OrderId"'.

Summary

Brands stop values with the same underlying type from being mixed up. Next, readonly arrays.

Key takeaways
  • number & { __brand }
  • Create with helpers
  • No mix-ups
Next up: Readonly Arrays — immutability