Skip to content

Lesson 9 of 9 · 27m

Branded Types and API Design That Prevents Bugs

Opaque IDs, validated strings, careful escape hatches, and library API types that guide users toward correct usage without constant annotations.

Some of the worst production bugs are type-correct and domain-wrong: a user id passed where an organization id belongs, a slug treated as a display name, a raw HTML string inserted where sanitized HTML was expected. They are all strings, so the compiler happily watches the accident happen. Branded types let you distinguish values that share a runtime representation but not a meaning.

Brand the meaning, not the syntax

declare const brand: unique symbol;

type Brand<T, Name extends string> = T & { readonly [brand]: Name };

type UserId = Brand<string, "UserId">;
type OrganizationId = Brand<string, "OrganizationId">;

function transferOwnership(userId: UserId, orgId: OrganizationId) {
  // ...
}

The brand exists only in the type system. At runtime it is still a string, so there is no serialization overhead. Constructors or validators create branded values:

function parseUserId(input: unknown): UserId {
  if (typeof input !== "string" || !/^usr_[a-z0-9]{24}$/.test(input)) {
    throw new TypeError("invalid user id");
  }
  return input as UserId;
}

Now transferOwnership(orgId, userId) fails at compile time even though both are strings at runtime.

API types should make the correct path easy

A well-designed library API uses inference so users do not annotate everything:

function createQuery<Input, Output>(config: {
  parse: (input: unknown) => Input;
  run: (input: Input) => Promise<Output>;
}) {
  return { execute: (raw: unknown) => config.run(config.parse(raw)) };
}

const invoiceQuery = createQuery({ parse: parseInvoiceFilter, run: (filter) => db.invoices.search(filter) });

filter is typed without a manual annotation because it flows through the generic relationship. That is good API design: the type system carries context across the boundary instead of forcing users to repeat it.

Escape hatches need fences

Sometimes you need as, any, or @ts-expect-error — generated code, legacy adapters, browser inconsistencies. Fine. Make the escape hatch narrow, local, and explained by the shape of the code. @ts-expect-error is better than @ts-ignore because it fails when the underlying issue is fixed and the suppression becomes stale.

Field notes

  • Brand IDs at parse boundaries, not everywhere. Over-branding internal values creates conversion noise with no benefit.
  • unique symbol brands can be hard to reconstruct across declaration boundaries; export the type and constructors together.
  • Type-level tests with tsd or expect-type are essential for public APIs because inference regressions are behavioral breaking changes.
  • When users must write casts to use your API normally, the API types are wrong — not the users.

Was this lesson helpful?

Sign in to rate