Type System Deep Dive
Branded Types / Nominal Typing
Master Branded Types (Nominal Typing) in TypeScript, preventing accidental assignments between structurally identical primitive types (UserId vs OrderId).
TypeScript uses a Structural Type System. This means that if two types have the same shape, TypeScript treats them as completely interchangeable:
To solve this, developers use Branded Types (also called Nominal Typing or Opaque Types) to force TypeScript to treat structurally identical primitives as distinct, unique types.
1. How Branded Types Work
A Branded Type attaches an un-instantiated, unique property tag (the "brand") to a primitive type using an intersection:
2. Smart Constructor Helper Functions
To instantiate branded values, use small constructor helper functions that validate or assert the brand:
3. Financial & Currency Domain Protection
Branded types prevent mixing up different currency units or un-sanitized user data:
4. Interactive Code Playground
Test branded types below:
5. Summary Table
| Feature | Structural Typing (Default) | Branded Typing (Nominal) |
|---|---|---|
| Matching Rule | Based on property structure/shape | Based on explicit type name / brand tag |
string vs UserId | Interchangeable | Distinct types (Compile Error on mismatch) |
| Runtime Overhead | Zero | Zero (Brand tags are compile-time only) |