Skip to the solution
MediumFrontend10 min read

What are branded (nominal) types?

156 views

The problem

Question presented to candidate: "TypeScript is structurally typed, so a UserId and an OrderId that are both strings can be swapped by accident. How would you make the compiler tell them apart, and what does that cost at run time?"

What a strong answer should cover:

  • Structural typing: two aliases of string are the same type, so aliases alone give no protection
  • A brand intersects the base type with a fake property, string & { readonly __brand: "UserId" }, so plain strings and other brands are no longer assignable
  • Brands are created in one place, a smart constructor or a type guard / assertion function that validates and then casts, so the type means "already checked"
  • The brand is type-only: zero run-time cost, the value is still a normal string (typeof is "string"), and operations like .trim() or + return the unbranded base type
  • A unique symbol key and a generic Brand<T, B> helper make brands harder to fake and reusable; units of measure (Meters, Seconds) are a classic use
  • Alternatives and neighbours: classes with a #private field are nominal, string enums are opaque, and validation libraries offer brand helpers

Code / implementation expected: Yes β€” define two branded ID types, a constructor for each, and show a call that swaps them failing to compile.

  • branded-types

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptBranded IDs and a smart constructor
TypeScriptA Brand helper, units, validated values and #private classes

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 62 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What does `verbatimModuleSyntax` enforce and why did it replace `importsNotUsedAsValues`?

Continue