Branded and nominal types
Go from the first annotated variable to writing your own conditional, mapped and infer-based utility types, while keeping a clear line between compile-time checking and runtime behavior.
What you will be able to do
#- Create a brand with a phantom property or intersection.
- Prevent mixing structurally identical primitives.
- Keep brands compile-time only.
Overview
#The problem
type UserId = string and type OrderId = string are interchangeable because TypeScript is structural. A function that takes a UserId accepts an OrderId.
A brand
type Brand<T, B extends string> = T & { readonly __brand: B };
type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;
Now UserId and OrderId are not assignable to each other.
Creating a branded value
The brand is a compile-time fiction, so a cast is the normal constructor.
function userId(value: string): UserId {
return value as UserId;
}
Validation belongs in that constructor, not in the cast.
Alternative: unique symbol
declare const brand: unique symbol;
type Branded<T, B> = T & { readonly [brand]: B };
A unique symbol key cannot be forged structurally, which is stricter than a string key.
Cost
Brands add no runtime code and no runtime safety. They are a discipline tool: they stop you passing the wrong id, but the value is still a plain string at runtime.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
Does this compile? ```ts type UserId = string & { __brand: "UserId" }; type OrderId = string & { __brand: "OrderId" }; const u: UserId = "a" as UserId; const o: OrderId = u; ```
Exercise 2Implement
Implement a `Brand` helper and branded `UserId` and `OrderId` types, plus a `userId` constructor that trims and rejects empty input.
starter.typescriptexport type Brand<T, B extends string> = T & { readonly __brand: B }; export type UserId = Brand<string, "UserId">; export type OrderId = Brand<string, "OrderId">; export function userId(value: string): UserId { // your code }Reveal the reference answer
reference.typescriptexport type Brand<T, B extends string> = T & { readonly __brand: B }; export type UserId = Brand<string, "UserId">; export type OrderId = Brand<string, "OrderId">; export function userId(value: string): UserId { const trimmed = value.trim(); if (trimmed.length === 0) throw new Error("empty id"); return trimmed as UserId; }Authored expected output: Compiles with no errors. Runtime: userId(" a ") returns "a"; userId("") throws.
The cast applies the brand after a real runtime check.
Exercise 3Explain
Why does a unique symbol brand resist forgery better than a string-key brand?
Reveal the reference answer
reference.typescriptA string-key brand can be satisfied by any value that happens to have that property, because structural typing only checks shape. A unique symbol key cannot be created outside the module that declares it, so no other type can accidentally or deliberately satisfy the brand. That makes the brand a true nominal marker.Authored expected output: A written answer naming structural assignability and the non-forgeable symbol key.
Structural typing can be imitated; a unique symbol cannot.
Common misconceptions
#- A brand validates the value at runtime.
- Brands exist as objects at runtime.
- Any string-key brand is unforgeable.
Follow-up practice
#- typescript-recursive-types
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.