Branding nominal types

Structural collisions

TypeScript compares object shapes, not names, so two string ids look identical to the checker. A user id can flow into an order id slot with no warning at all.

The bug surfaces far from its cause: a mistyped argument fetches the wrong record. Branding gives each id a distinct type while keeping strings at runtime. The program passes a user id to a function that wants an order id and prints the result, which is exactly the mixup the checker allows.

function loadOrder(id: string): string { return "order:" + id; } const userId = "user-7"; console.log(loadOrder(userId));

order:user-7

Brand with a tag

A brand is an extra phantom field intersected with a plain type. It exists only for checking, never at runtime, yet it makes two string aliases incompatible.

Name the brand after the concept it protects. Clear brand names turn idle strings into documented domain values across the whole file. The program builds one value of each brand and prints them.

type UserId = string & { readonly brand: "UserId" }; type OrderId = string & { readonly brand: "OrderId" }; const u: UserId = "user-7" as UserId; const o: OrderId = "order-9" as OrderId; console.log(u, o);

user-7 order-9

Use branded ids

Constructors validate raw text once and return the branded result. After that point every function can demand the exact brand and reject lookalike strings.

Push validation to the edges: parse at input, then enjoy precise types inside. The middle layers stay short because wrong ids no longer compile. The program makes one id and greets it, then tries an empty raw id and catches the message.

type UserId = string & { readonly brand: "UserId" }; function makeUserId(raw: string): UserId { if (raw.length === 0) { throw new Error("Empty user id"); } return raw as UserId; } function greetUser(id: UserId): string { return "hi " + id; } console.log(greetUser(makeUserId("user-7"))); try { makeUserId(""); } catch (err: unknown) { console.log((err as Error).message); }

hi user-7
Empty user id

Escape hatch

Sometimes you must drop back to a plain string, for example to build a URL or write a log line. A tiny helper converts a branded id to its raw text in one visible step.

Keep escapes rare and explicit at boundaries. If raw text leaks everywhere, the brand loses value and mixups return through the back door. The program converts a branded id back to its text and prints it.

type UserId = string & { readonly brand: "UserId" }; function makeUserId(raw: string): UserId { if (raw.length === 0) { throw new Error("Empty user id"); } return raw as UserId; } function rawId(id: UserId): string { return id as string; } console.log(rawId(makeUserId("user-7")));

user-7

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Why do two string ids collide in TypeScript?

    Answer

    The checker compares shapes, and both are strings

    A structural type system sees the same shape in two different meanings.

  2. What is a brand in TypeScript?

    Answer

    A phantom field intersected with a plain type

    The field exists only for the checker, so the value stays a string at run time.

  3. Where should raw text become a branded id?

    Answer

    At the edge, where the value enters the program

    One validated entry point lets every middle layer demand the brand and stay short.

  4. Why keep the escape back to a plain string explicit?

    Answer

    Rare and visible escapes keep the brand meaningful

    Raw text leaking everywhere would bring the mixups back through the back door.

  5. What does this program print? type UserId = string & { readonly brand: "UserId" }; function greetUser(id: UserId): string { return "hi " + id; } const id = "user-7" as UserId; console.log(greetUser(id));

    Answer

    hi user-7

    The brand changes nothing at run time, so the string joins the greeting as usual.

  6. What does this program print? type UserId = string & { readonly brand: "UserId" }; type OrderId = string & { readonly brand: "OrderId" }; function loadOrder(id: OrderId): string { return "order:" + id; } console.log(loadOrder("order-9" as OrderId));

    Answer

    order:order-9

    The cast makes the value an order id for the checker, and the runtime value is still the same text.

  7. What does this program print? type UserId = string & { readonly brand: "UserId" }; function makeUserId(raw: string): UserId { if (raw.length === 0) { throw new Error("Empty user id"); } return raw as UserId; } try { makeUserId(""); } catch (err: unknown) { console.log((err as Error).message); }

    Answer

    Empty user id

    The empty text fails the check, and the catch prints the message of the thrown error.

  8. What does this program print? type UserId = string & { readonly brand: "UserId" }; const id = "user-7" as UserId; function rawId(value: UserId): string { return value as string; } console.log(rawId(id).toUpperCase());

    Answer

    USER-7

    The escape gives a plain string back, and the string method works on it.

  9. What does the compiler say about this program? type UserId = string & { readonly brand: "UserId" }; type OrderId = string & { readonly brand: "OrderId" }; function loadOrder(id: OrderId): string { return "order:" + id; } const userId = "user-7" as UserId; console.log(loadOrder(userId));

    Answer

    error TS2345: Argument of type 'UserId' is not assignable to parameter of type 'OrderId'.

    The two brands are different types, and the compiler refuses one where the other is required.

  10. What does the compiler say about this program? type UserId = string & { readonly brand: "UserId" }; const id: UserId = "user-7"; console.log(id);

    Answer

    error TS2322: Type 'string' is not assignable to type 'UserId'.

    A plain string lacks the brand field, so it needs the cast or a constructor that returns a branded value.

Article author: Arthur Isaev