Testing & Code Quality
Runtime Validation
Runtime validation checks actual values while the program runs. It complements TypeScript by proving that untrusted input matches the type the rest of the code wants to use.
- Validation is runtime evidence
- Parsing is better than checking-and-continuing
- Validation should report useful errors
- Schemas reduce type drift
- Validate as close to the boundary as possible
type User = { id: string; name: string }
function parseUser(value: unknown): User {
if (typeof value !== "object" || value === null) {
throw new Error("User must be an object")
}
const candidate = value as { id?: unknown; name?: unknown }
if (typeof candidate.id !== "string") throw new Error("User.id must be string")
if (typeof candidate.name !== "string") throw new Error("User.name must be string")
return { id: candidate.id, name: candidate.name }
}| Style | Shape | Use when |
|---|---|---|
| Throwing parser | returns T or throws | Invalid input is exceptional at this layer |
| Result parser | success/error union | Caller should recover or report multiple errors |
| Boolean guard | value is T | Simple branching |
| Assertion function | asserts value is T | Abort current path on invalid input |