Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readTypeScript

Branded types to stop mixing up IDs

Brand string IDs so TypeScript rejects a UserId passed to a function that expects an OrderId.

You gave UserId and OrderId their own type aliases, then passed a user id to cancelOrder. TypeScript accepts the call, so the order function gets a user ID.

type UserId = string
type OrderId = string

function cancelOrder(orderId: OrderId) {
  console.log(`cancelling ${orderId}`)
}

const userId: UserId = 'u_42'
cancelOrder(userId) // compiles

Running tsc --strict --target es2020 --noEmit trap.ts prints nothing and exits 0. An alias is another name for string, and TypeScript compares types by their structure. Both aliases describe string.

Give each id a brand

Add a property that exists only in the type system, with a different literal type per id. Brand intersects string with that property.

type Brand<T, Name extends string> = T & { readonly __brand: Name }

type UserId = Brand<string, 'UserId'>
type OrderId = Brand<string, 'OrderId'>

const asUserId = (value: string) => value as UserId
const asOrderId = (value: string) => value as OrderId

function cancelOrder(orderId: OrderId) {
  console.log(`cancelling ${orderId}`)
}

const userId = asUserId('u_42')
const orderId = asOrderId('o_7')

cancelOrder(orderId) // ok
cancelOrder(userId)
// error TS2345: Argument of type 'UserId' is not assignable to parameter of type 'OrderId'.
cancelOrder('o_7')
// error TS2345: Argument of type 'string' is not assignable to parameter of type 'OrderId'.

Run tsc --strict --target es2020 --noEmit brand.ts and both bad calls fail with the errors above. Both constructors currently accept any string. Add validation before trusting an ID from outside your code.

Where the casts go

Keep the assertion in the parser for each ID type. Replace the earlier asOrderId with this version when taking an ID from a request or a database row.

const asOrderId = (value: unknown): OrderId => {
  if (typeof value !== 'string' || !/^o_\d+$/.test(value)) {
    throw new Error('Expected an order ID like o_7')
  }
  return value as OrderId
}

This parser checks the ID's format. The order lookup still needs to establish that the order exists.

A branded ID is still a string at runtime and is assignable to string. const raw: string = orderId compiles, template literals work, and orders.get(userId) on a Map<OrderId, string> is an error, so maps keyed by different ids stay apart. The __brand property is never set on any value, so don't read it.

I add a brand when two ids share a primitive type and travel through the same function signatures. A single id: string in a small module doesn't need one.