Branded (nominal or "opaque") types add a phantom marker to a type so that structurally identical values aren't interchangeable: type UserId = string & { readonly __brand: 'UserId' }. A plain string (or an OrderId) can no longer be passed where a UserId is expected. Values get the brand only through a constructor or validation function (often the single place that casts), so the brand also means "this value has been checked" (Email, PositiveInt, SanitizedHtml). At runtime it's still just a string, so there's zero cost.
function chargeOrder(orderId: string, userId: string) {}
chargeOrder(user.id, order.id); // swapped arguments: compiles fine
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type UserId = Brand<string, 'UserId'>;
type OrderId = Brand<string, 'OrderId'>;
const UserId = (raw: string) => raw as UserId; // the only cast, in one place
const OrderId = (raw: string) => raw as OrderId;
function chargeOrder(orderId: OrderId, userId: UserId) {}
const u = UserId('u_1');
const o = OrderId('o_9');
chargeOrder(o, u); // OK
chargeOrder(u, o); // error: UserId is not assignable to OrderId
chargeOrder('o_9', u); // error: string is not assignable to OrderId
Using a unique symbol key (declared but never created) keeps the brand from appearing in autocomplete as a real property and prevents accidental collisions. A simpler { __brand: 'UserId' } works too.
Branded values are still assignable to the base type (const s: string = u; is OK), so they work with any string API.
type Email = Brand<string, 'Email'>;
function parseEmail(input: string): Email | null {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input) ? (input as Email) : null;
}
function sendWelcome(to: Email) { /* no need to re-validate */ }
const email = parseEmail(form.email);
if (email) sendWelcome(email);
sendWelcome(form.email); // error: must go through parseEmail
Other useful brands: PositiveInt, Cents vs Dollars, Iso8601, SafeHtml, AbsolutePath, Celsius vs Fahrenheit.
Zod (z.string().uuid().brand<'UserId'>()), Valibot and Effect Schema can produce branded types from runtime validation. This is a clean way to brand IDs coming from APIs at the trust boundary.
class UserId { #v: string }) are truly nominal but add runtime objects and need .value unwrapping.`usr_${string}`) give partial safety if your ids have prefixes. They're structural but catch many mix-ups without casts.as UserId inside the constructor or parser module, and lint against it elsewhere.(a as Cents) + (b as Cents) is number. Provide helper functions.Spotted a mistake or a rights concern? Report an issue