WebMriya
Back to articles

Branded Types in TypeScript: Prevent ID Mix-Ups

Use branded types to keep distinct IDs and units from being mixed accidentally, with runtime constructors that make the boundary explicit.

TypeScript
Frontend Architecture
Software Architecture
W
Frontend Architecture & Legacy Modernization
October 26, 2026 · 5 min read

A function expects a project ID, but receives a user ID. Both are strings, so TypeScript accepts the call—and the bug may only appear when the wrong record is loaded. The same problem happens with quantities: a value in cents is passed to code expecting dollars, or one tenant’s identifier is used where another is required. These mistakes are easy to make when a codebase represents every identifier and measurement with the same primitive type. Branded types add a compile-time distinction without changing the underlying runtime value, helping make invalid combinations harder to express.

What a branded type changes

TypeScript is structurally typed: if two values have the same structure, they are generally compatible. That is convenient for everyday objects, but it means `UserId` and `ProjectId` are interchangeable if both are aliases for `string`. A brand adds a marker to the type that exists only in the type system. The JavaScript value remains a string, but the compiler can now distinguish the two named concepts. This does not validate data at runtime, secure an API, or alter JSON. It gives the compiler a stronger model of which values may be passed to which functions.

ts
declare const brand: unique symbol;
type Brand<Value, Name extends string> = Value & {
  readonly [brand]: Name;
};

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

function openProject(id: ProjectId) {
  // Load the project identified by id.
}

With those definitions, a plain string is not automatically accepted as either ID, and a `UserId` cannot be supplied where a `ProjectId` is expected. The distinction is useful at function boundaries: a function’s signature can communicate which identifier it needs, and incorrect calls can fail during development instead of silently compiling. The brand is intentionally not a runtime tag. At runtime, both values are still strings, so serialization stays simple and existing APIs need not change.

Create branded values at a deliberate boundary

A brand is only useful if values enter the typed part of the application through controlled constructors. A direct assertion such as `value as ProjectId` can silence the compiler anywhere, so it should be kept inside a small, named function rather than repeated throughout the codebase. The constructor below accepts a string and checks a minimal condition. Replace that condition with the actual rules for your identifiers; do not assume that a non-empty string is sufficient for every system.

ts
function parseProjectId(value: string): ProjectId {
  if (value.length === 0) {
    throw new Error("Project ID must not be empty");
  }

  return value as ProjectId;
}

const projectId = parseProjectId(apiResponse.projectId);
openProject(projectId);

This constructor does not make an untrusted value trustworthy by magic. It documents and enforces only the check it actually performs. If the identifier has a specific format, validate that format here; if API payloads may be malformed, validate the payload at the boundary before trusting its fields. A branded type is a compile-time guarantee after construction, not a substitute for runtime validation. For a broader approach to that boundary, see TypeScript Runtime Validation: Close the Gap at API Boundaries.

Where brands pay off

Use brands where two values share a primitive representation but have different meanings and mixing them would cause a meaningful error. Common examples are user, organization, and project IDs; currency amounts expressed in different units; timestamps measured in seconds versus milliseconds; and values that have passed a particular validation step. They are most valuable where a wrong value can cross a service or feature boundary unnoticed. For a local temporary variable used in one small function, the extra type machinery may add more ceremony than protection.

  • Brand identifiers that belong to different entities, especially when functions accept multiple IDs.
  • Brand measurements or amounts when their units must not be confused.
  • Use a named constructor to keep assertions localized and explain how values enter the typed domain.
  • Keep ordinary strings and numbers ordinary when their meaning is already clear from the local context.

Brands can also represent a state transition. For example, a raw email string and an email string that has passed a format check can have separate types. That distinction helps prevent a function that sends notifications from accepting unchecked input. But be precise about what the type proves: a format check does not prove that an address exists, belongs to a particular person, or can receive mail. The name of the brand should describe the guarantee the constructor actually establishes—not a stronger claim.

Trade-offs and common mistakes

The main cost is friction at creation points. Data from forms, URLs, storage, and APIs arrives as ordinary strings or numbers, so it must be parsed or validated before it can be used as a branded value. That friction is useful when it marks a real boundary, but repetitive casting defeats the point. Another risk is spreading brands through an application before there is a clear need. Brands can complicate test fixtures, generic helpers, and interactions with libraries whose types expect plain primitives. Introduce them around a concrete class of mix-ups and keep conversions visible.

Avoid treating a brand as access control. Because the marker is erased at runtime and TypeScript assertions are available, a developer can still forge a branded value. Do not rely on it to enforce permissions, tenant isolation, or security-sensitive rules; those belong in runtime checks and on the server. Also avoid brands that duplicate information the program cannot meaningfully verify. A type that says “authorized user” is misleading unless the code that creates it performs and controls the relevant authorization decision.

A practical adoption checklist

  1. Find a real bug risk: two same-shaped values can be swapped, and the result matters.
  2. Define a small shared brand helper and use specific names for each concept.
  3. Add constructors at trusted application boundaries, with checks that match the real data contract.
  4. Replace broad casts with constructor calls and let compiler errors reveal missing conversions.
  5. Keep serialization and API contracts unchanged unless the external system itself needs to change.
  6. Review whether the brand communicates a real invariant; remove it if it only adds ceremony.

Branded types work best as a narrow layer on top of familiar TypeScript, not as a type-system project of their own. Start with the IDs or units that have caused confusion, make their creation explicit, and keep runtime validation separate from compile-time distinctions. If these boundaries are becoming difficult to maintain across a React codebase, WebMriya’s Product UI Development work can help structure the interfaces and data flows around them.

Frequently asked questions

Do branded types change the value at runtime?

No. A branded string is still a string at runtime, so JSON serialization remains unchanged. The distinction is enforced by TypeScript during development.

Can a branded type replace runtime validation?

No. A brand records a compile-time distinction after a value has been constructed. Validate external data at runtime before creating the branded value.

When should I use branded types?

Use them when values share a primitive type but represent different concepts that could be accidentally interchanged. Skip them when the distinction adds ceremony without preventing a realistic mistake.