Typed Results and Errors
- Result types. A Result union: {ok: true; value: T} | {ok: false; error: E}: makes failure part of the signature.
- Expected versus thrown. Model expected failures as values and keep throw for genuine bugs: callers then handle what they must.
- Error unions. Naming each failure as a variant gives callers an exhaustive switch: no forgotten case survives review.
Exhaustiveness
- The never trick. Assigning the leftover value to never in a default branch turns “handled every case” into a compile-time fact.
- Adding a variant safely. Add a new variant and every unhandled switch fails to compile: the type system running your TODO list.
- Exhaustive maps. A Record keyed by a union forces one entry per variant: configuration made complete by construction.
Designing Impossible States Out
- States as unions. Replace flag soup with one state union: loading with data or error simply stops existing.
- Parse, don’t validate. Parse raw input into a rich type once at the edge: beyond that line, the data is proven, not re-checked.
- Types as documentation. A precise type is documentation that cannot rot: it fails the build the day it stops being true.
Before and after this level
- Before: Level 11: Libraries & Declarations: Declaration Files, Third-Party Type Definitions, Publishing Typed Libraries.
- Next: Level 13: Testing & Refactoring: Testing Typed Code, Type-Safe Refactoring, Maintaining Large TypeScript Codebases.
In the app each of these ideas is taught and then asked back, and the level ends with a checkpoint and flashcards. See Checkpoints and flashcards.
Frequently asked questions
What does TypeScript Level 12: Error Modelling cover?
Typed Results and Errors, Exhaustiveness, Designing Impossible States Out: 3 lessons and 9 ideas.
What should I know before this level?
The level before it, Level 11: Libraries & Declarations, which covers Declaration Files, Third-Party Type Definitions, Publishing Typed Libraries.