Skip to content

Branded IDs

The Course
•
25 min study

Structural typing normally treats two strings alike, even if one represents a book id and another represents a user id. An intersection can add a compile-time marker: BookId is a string AND a record with a private brand key. This is the ampersand's meaning in a type: both requirements must hold.

Understand the bracketed key

A JavaScript symbol is a distinct property key. Symbol("tag") creates one; the label is for debugging, not a string key. In an object literal, brackets compute a property name from a value. Reading the same bracketed key retrieves it.

A symbol property keyTypeScript
const tag = Symbol("tag");
const record = { [tag]: "book" };

console.log(record[tag]);
console.log("tag" in record);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
book
false

The brand below uses similar bracket syntax only in a type. It does not add a symbol property to a string. Read its pieces separately: declare introduces a checking-only name, unique symbol gives that name a distinct key type, and readonly prevents assignments through that marker type.

declare const bookIdBrand: unique symbol declares a distinct symbol type for checking; declare emits no JavaScript variable. We use that symbol only as a computed type key, never as a runtime property. The string returned by the factory is still an ordinary string at runtime.

The factory below is the one audited assertion boundary. It first checks the exact rule—nonblank text after trimming—then asserts that validated string as BookId. The assertion does not perform the check; the preceding code is the evidence. Export the type and factory from a module while keeping its brand key private.

A brand prevents accidental mixing by cooperative TypeScript callers. It is not authorization, a secret token, a guarantee against casts, or proof that a book exists in a database. Keep its claimed meaning narrow and test the factory's normalization and rejection rules.

Predict, check, and run

Write the output before running. Use Check types first, then Check & run. Types disappear at runtime: explain both what the compiler checks and what the code actually does. Each editor is an independent ES module; await asynchronous work explicitly.

Predict, then runTypeScript
declare const brand: unique symbol;

type BookId = string & { readonly [brand]: "BookId" };

function bookId(value: unknown): BookId | null {
  if (typeof value !== "string" || value.trim() === "") {
    return null;
  }

  return value.trim() as BookId;
}

console.log(bookId(" b1 "));
console.log(bookId(" "));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
b1
null

Read the compiler error

Predict the rejected relationship before checking. Read the real diagnostic and its source location; fix the contract or the value instead of hiding it with an assertion.

Find and fix the type errorTypeScript
declare const brand: unique symbol;

type BookId = string & { readonly [brand]: "BookId" };

const id: BookId = "b1";

console.log(id);

Enable JavaScript to edit and type-check this example.

Check your diagnosis

The key line is TS2322: Type 'string' is not assignable to type 'BookId'. The second line expands BookId to the brand property { readonly [brand]: "BookId" }: that hidden property is the part a plain string lacks.

A plain string has not satisfied the branded contract. Obtain it from the checked factory; do not scatter assertions around call sites.

Two brands do not mix

The real payoff is between two branded types. Both ids below are strings at runtime, and the arguments are swapped. Without brands this would compile and print the wrong sentence. (The one-line factories skip validation to keep the focus on the call.)

Find and fix the type error: swapped idsTypeScript
declare const brand: unique symbol;

type BookId = string & { readonly [brand]: "BookId" };
type UserId = string & { readonly [brand]: "UserId" };

const bookId = (value: string) => value as BookId;
const userId = (value: string) => value as UserId;

function borrow(book: BookId, user: UserId): string {
  return `${user} borrows ${book}`;
}

const book = bookId("b1");
const user = userId("u7");

console.log(borrow(user, book));

Enable JavaScript to edit and type-check this example.

Check your diagnosis

The key line is TS2345: Argument of type 'UserId' is not assignable to parameter of type 'BookId'. Read down to the last line, Type '"UserId"' is not assignable to type '"BookId"': the brand tags are the only difference, and that difference is the whole point. Swap the arguments to borrow(book, user); it prints u7 borrows b1.

Debug a plausible mistake

Exercise

Repair the branded factory evidence

Normalize valid IDs and reject blank input. Print true then true. Keep the single audited assertion inside the factory; the runtime validation and normalization must justify its claim.

Predict the supplied program's actual behavior first. It compiles, but violates the requirement. Make a small repair, then try a case that would distinguish the repaired version from the original.

Debugging workspaceTypeScript
declare const idBrand: unique symbol;
type BookId = string & { readonly [idBrand]: "BookId" };

function bookId(value: unknown): BookId | null {
  if (typeof value !== "string" || value.trim() === "") {
    return null;
  }
  return value as BookId;
}

console.log(bookId(" b1 ") === "b1");
console.log(bookId(" ") === null);

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

A brand does not perform the transformation its factory promises.

Hint 2: a first step

Return the normalized validated string, not the original spelling.

Show one solution
TypeScript
declare const idBrand: unique symbol;
type BookId = string & { readonly [idBrand]: "BookId" };

function bookId(value: unknown): BookId | null {
  if (typeof value !== "string" || value.trim() === "") {
    return null;
  }
  return value.trim() as BookId;
}

console.log(bookId(" b1 ") === "b1");
console.log(bookId(" ") === null);
Text
true
true

The original validated the trimmed text but returned the untrimmed value, so bookId(" b1 ") was " b1 " and the first line printed false. The brand compiled either way: as BookId trusts the factory, it does not check that the returned value matches what was validated. Returning value.trim() makes the asserted value the same one the check approved.

Trace the contract before building

A brand records that code has passed through an audited construction boundary. The factory must actually enforce the promised rule before applying the brand. A cast elsewhere can counterfeit that evidence, so keep assertions narrow and reviewable rather than scattering them through consumers.

Explain the runtime representation and the additional meaning the brand expresses. If the factory promises normalized identifiers, test padded input and compare the returned text as well as its declared type. Then test rejected input. A type-level test that two brands cannot be mixed will not catch a factory that labels unnormalized text as valid.

Build it yourself

Exercise

Branded IDs: practice

Create a branded UserId and a checked factory returning UserId|null. Accept and trim " u1 ", reject 25 and blanks. Print u1 and true for rejection. Keep the assertion only after validation.

Your workspaceTypeScript
// Start from the stated contract. Add a valid call and an edge case.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

The brand marker is type-only; runtime evidence must come from the factory body.

Hint 2: a first step

Narrow to string, trim once, reject empty text, then assert the normalized value.

Show one solution
One possible solutionTypeScript
declare const userIdBrand: unique symbol;

type UserId = string & { readonly [userIdBrand]: "UserId" };

function userId(value: unknown): UserId | null {
  if (typeof value !== "string") {
    return null;
  }

  const normalized = value.trim();

  if (normalized === "") {
    return null;
  }

  return normalized as UserId;
}

if (userId(" ") !== null) {
  throw new Error("Blank id accepted");
}

console.log(userId(" u1 "));
console.log(userId(25) === null);

Enable JavaScript to edit and type-check this example.

Text
u1
true

Trimming once into normalized means the check and the returned value cannot drift apart, which was the bug in the debug exercise. The as UserId assertion is the only one, and it comes after every rule has been checked. Because UserId and the lesson's BookId have different brand tags, a UserId from this factory cannot be passed where a BookId is required.

Change it and test it

Create separate BookId and UserId types and try passing one where the other is required. Then remove the factory validation and explain why the cast still compiles while runtime tests expose the lie.

Was this article helpful?

Your response is saved on this device.