New: Cookbooks and AI ExplanationsStep-by-Step recipes to solve problems connected to Roadmaps and Cheat Sheets. Need more details? Use AI buttons for structured and simple explanations with concrete examples throughout the whole platform.Take a look
My API call returns either data or an error, and half my code has to guess which one it got.
What you'll have at the end
A response type where a switch that reads the wrong branch's field, or skips a branch entirely, fails to compile instead of failing at 2am.
You need
A TypeScript project with strict type checking on, and an async function that already calls a real HTTP endpoint and reads its JSON body back.
Not covered
Checking that a parsed response's fields actually hold the right runtime values once the JSON arrives (the body itself could still lie about its own shape), and sharing one outcome type across several unrelated endpoints.
Leans on
Giving a fetch response a real type instead of any
For an endpoint that always sends one predictable shape, with no separate success or failure branch to model at all.
Narrow an unknown JSON value before you trust it
For confirming a response's fields actually hold the runtime values this recipe's type only promises at compile time.
Force an exhaustive switch that breaks the build on a missed case
For the same never-based exhaustiveness pattern applied to a status value already flowing through an existing codebase, rather than one built from scratch here.
Checked 22 Aug 2026
Part of the TypeScript cookbook