Explainers · Short
Return errors as data in TypeScript
- Published
- Duration
- Language
- English
Summary
Return errors as data in TypeScript. A pure function returns the same output for the same input and has no side effects. A function that throws has a second, invisible exit, and nothing in its type tells you it is there. The alternative is to return failure as data: the function parseAge never throws, it returns a status plus the data or the reason it failed. TypeScript will not let you read the data property until you have checked the ok property, and an exhaustive switch reports any error case you forgot to handle. Libraries still throw, so wrap them once, at the edge, with an attempt function that runs the call inside try and catch and turns the exception into a result. Start with the one function closest to the outside world. Keep throwing for real bugs; return expected failures as data.
Every snippet was checked with tsc strict mode on TypeScript 7.0.2 and 5.9.3.
Transcript
Text of the video's narration.
A pure function is simple: same input, same output, no side effects. Exceptions break that promise. A function that throws has a second, invisible exit, and nothing in its type tells you it's there. Here, parseAge never throws. It returns a status, plus the data or the reason it failed, and the error type lists every possible reason.
You can't read r.data until you've checked r.ok, and an exhaustive switch flags any error case you forgot to handle. But libraries still throw. So wrap them once, at the edge: attempt runs the call inside a try-catch and turns the exception into a result.
Start with one function, the one closest to the outside world, and make it return a result. Keep throwing for real bugs. For expected failures, return them as data.
Sources
- TypeScript handbook, Narrowing (discriminated unions, the never type and exhaustiveness checking) typescriptlang.org
- MDN, JSON.parse (throws SyntaxError if the string is not valid JSON) developer.mozilla.org
- MDN, try...catch developer.mozilla.org
- MDN, fetch (the promise rejects on a network error) developer.mozilla.org
Credits and notes
- Narrated with Phonon; motion in Remotion.



