Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Concepts and Comparisons

Branded types in TypeScript

Make structurally identical types incompatible with branded types: IDs, units and validated strings, with brand creation and safe constructors.

Structural typing means two types with the same shape are interchangeable. That is usually helpful, but it lets you pass a ProductId where a UserId is expected when both are plain string. A branded type adds a phantom marker so the compiler treats them as different types.

The brand exists only in the type system. At run time the value is still the original string or number, so there is no cost.

TypeScript
type UserId = string & { readonly __brand: "UserId" };

Try it

TypeScript Two IDs that cannot be mixed up

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript The compiler rejects the wrong brand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Units of measure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

How it works

A brand is an intersection of the base type and an object with a unique marker property. A plain string lacks the marker, so it is not assignable to UserId; a UserId is still assignable to string, so every string function keeps working.

You create a branded value in exactly one place: a constructor or parser that checks the input, then asserts the brand. Everything downstream can trust it.

Usage notes

  • The brand is a promise. as UserId is an assertion; guard it with validation so the promise is true.
  • Use unique symbol for the marker if you want the brand property to be impossible to mention accidentally; a string key is easier to read in errors.
  • Type predicates like isUserId(x): x is UserId can create brands from checks.
  • Arithmetic loses brands. meters + meters is a number again; wrap the result in a helper.
  • Classes with #private fields give nominal behavior for objects without a brand; see Class structural compatibility.
  • JSON and databases return plain values; brand them at the boundary.
  • Opaque types are the same idea under another name; some libraries ship a Brand helper.