Menu

1 / 2

Opaque Types Without `unique symbol`: A Lighter Branded-Types Pattern

DEV Community·Gabriel Anhaia·6 months ago
#eVCGe9la
#typescript#types#generics#brand#string
Reading 0:00
15s threshold

Book: The TypeScript Type System — From Generics to DSL-Level Types

Also by me: The TypeScript Library — the 5-book collection

My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools

Me: xgabriel.com | GitHub

You have seen this bug. A function takes userId: string and

organizationId: string . Somewhere five files away, a developer

in a hurry passes them in the wrong order. The compiler accepts

it. The query runs. The wrong rows come back. The unit test

passes because the unit test fixture used the same string for

both.

string is the shape both arguments share. string is also the

shape every other ID in the codebase shares. The type system has

no way to tell UserId from OrgId from OrderId from any

other 26-character UUID, and so it does not.

Branded types fix this. The pattern most TypeScript codebases

reach for is unique symbol . It is the textbook answer.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.