Learning on Web Dev Open is free for all.

Systems Thinking > TypeScript as a design toolThe boundary is where your types stop being true
Phase 03TypeScript as a design tool163 of 434

The boundary is where your types stop being true

Everything from the network, the filesystem, localStorage or a form is unknown until something checks. A type annotation on a fetch result is a wish.

Concept14 minAI implements

TypeScript is erased. const user = await res.json() as User compiles to const user = await res.json(), and everything downstream is now trusting a claim nobody verified. The API changed a field to nullable last Thursday and your types still say otherwise; the failure appears wherever that field is first dereferenced, which is nowhere near the fetch.

The fix is to parse at the edge and infer the type from the parser, not the other way round. Whatever runtime schema library you use, the shape is the same: one definition, validated at the boundary, with the static type derived from it so the two cannot drift. Inside that boundary you can trust your types completely, which is the entire point of having them.

Where to put the boundary is a design decision worth making explicitly. Every HTTP response, every localStorage read, every URL parameter, every form submission, every message from a worker. Draw the line once per entry point and keep the interior clean, rather than sprinkling optional chaining through the codebase to defend against data you never checked.

You should now be able to

  • Parse untrusted input into a typed value at the edge
  • Explain why an interface on a JSON response proves nothing
Ask the community

Loading…