L06 Types and failure paths
19 minSuggested first: L05 Collections and mutation
Outcome
Distinguish a TypeScript annotation, a runtime guard, a returned failure, and a thrown error.
Learn
A TypeScript annotation documents and checks an expectation while you develop; it doesn't validate arbitrary input at runtime. A guard checks an actual value while the program runs.
A returned error-shaped value is ordinary data the caller can inspect. A thrown error leaves the normal path until a matching handler catches it.
Worked example
Predict the result of doubleNumber("3"), and of doubleNumber(3).
type Result = { ok: false } | { ok: true; value: number };
function doubleNumber(input: unknown): Result {
if (typeof input !== "number") return { ok: false };
return { ok: true, value: input * 2 };
}
Predict first, then show the worked explanation
The string "3" fails the guard on line 3 and returns { ok: false }. The number 3 passes
and returns { ok: true, value: 6 }. The different literal ok values let TypeScript narrow
the result after a caller tests result.ok.
Practice and check
Common mistake
Assuming an annotation converts a string into a number. Find the line that actually examines or converts the value.
Practice on a real repository
After the group checkpoint, try the Zod puzzle below. Read its prompt on its own terms: this lesson's example is unrelated to its answer.
- Building the failure result of safeParseFind · Easy · colinhacks-zod
Related topics: Validation and parsing, Errors
Practice is optional. Solving a puzzle doesn't complete a lesson, and lessons never change a puzzle's points.
References
- Narrowing (TypeScript Handbook)
- Basic usage (Zod documentation)