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.
type UserId = string & { readonly __brand: "UserId" };
Try it
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.
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.
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 UserIdis an assertion; guard it with validation so the promise is true. - Use
unique symbolfor 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 UserIdcan create brands from checks. - Arithmetic loses brands.
meters + metersis anumberagain; wrap the result in a helper. - Classes with
#privatefields 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
Brandhelper.