Skip to content

Branded and phantom types

Relay has a function cancelJob(jobId: string). Last week someone passed it a webhook id. Both are strings, so it compiled, and Relay cancelled nothing and logged no error. The same thing happens with durations: retryAfter(30) was meant to be seconds and the function reads milliseconds.

TypeScript compares types by shape. Two strings have the same shape, so they are the same type. A brand adds a fake property that exists only in the type, so the shapes differ and the compiler keeps the values apart. Nothing changes at runtime.

declare const brand: unique symbol
type Brand<T, Name extends string> = T & { readonly [brand]: Name }
type JobId = Brand<string, "JobId">
type WebhookId = Brand<string, "WebhookId">
declare const job: JobId
declare const hook: WebhookId
const s: string = job // a JobId is still a string
// @ts-expect-error: a WebhookId is not a JobId
const j: JobId = hook
// @ts-expect-error: a plain string is not a JobId
const k: JobId = "job_1"

declare const brand: unique symbol makes a key no other type can have. It is declared, never created, so nothing exists at runtime. string & { [brand]: "JobId" } is a string that also carries the brand. You can read it, slice it and pass it anywhere a string is expected. You just can’t get one by accident.

The same works for numbers. Brand<number, "Ms"> can’t be mixed up with a count of seconds.

If a plain string isn’t a JobId, how do you make one? In one place, after checking it. That function is a smart constructor. It is the only code that is allowed to say “trust me”:

declare const brand: unique symbol
type Brand<T, Name extends string> = T & { readonly [brand]: Name }
type JobId = Brand<string, "JobId">
type Result<T, E> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: E }
function parseJobId(input: string): Result<JobId, string> {
if (!/^job_[a-z0-9]+$/.test(input)) return { ok: false, error: `invalid job id: ${input}` }
return { ok: true, value: input as JobId }
}
declare function cancelJob(id: JobId): void
const parsed = parseJobId("job_42")
if (parsed.ok) cancelJob(parsed.value)

The as JobId is a cast, and normally you avoid those (M1). Here it is the point: it sits right behind the check, in one function. Every other place in Relay gets a JobId only by going through parseJobId. That is parsing at the boundary with a type to remember the result.

A brand marks what a value is. A phantom type parameter marks what has happened to it. The parameter appears in the type but no field holds it. Relay must not enqueue a webhook body before its signature is checked, so the request carries that fact:

declare const phantom: unique symbol
type ReqState = "unverified" | "verified"
interface Req<S extends ReqState> {
readonly body: string
readonly signature: string
readonly [phantom]?: S
}
declare function receive(body: string, signature: string): Req<"unverified">
declare function verify(req: Req<"unverified">, secret: string): Req<"verified"> | null
declare function enqueue(req: Req<"verified">): void
const raw = receive("{}", "sig")
// @ts-expect-error: an unverified request cannot be enqueued
enqueue(raw)
const ok = verify(raw, "secret")
if (ok !== null) enqueue(ok)

The optional [phantom]?: S field is what makes Req<"verified"> and Req<"unverified"> different types. Without any use of S, the compiler would see two identical shapes and accept one for the other, the same reason plain strings mix. This is the state machine from M2 with the states moved into the type: a function that only works in one state says so in its signature, and calling it in the wrong state doesn’t compile.

Every branded value needs a constructor and a place to call it, and tests and JSON need them too. Brand the values that were actually mixed up: ids that cross module borders, units that bite (milliseconds, cents). A name that is only used in one function does not need a brand. If the constructor never fails, ask whether a simple type alias or a parameter name would do.

Make JobId, WebhookId and Ms branded, write the smart constructors’ return types, and give Req its phantom state. Brand and the fake sign function are given. The tests check both the runtime results and which calls must not compile.

  • A brand is T & { readonly [brand]: Name }: same runtime value, different type.
  • A branded value is still its base type: a JobId works as a string.
  • Create branded values in smart constructors that validate, and keep the casts there.
  • A phantom parameter such as Req<"verified"> tracks state with no runtime cost. It must be used in the type, or the compiler sees identical shapes.
  • Brand what was really mixed up, not everything.