TypeScript for real code · Chapter 27 of 36
When things go wrong
By the end of this chapter you can handle anything a catch gives you, write error classes that carry typed data, and return failures as values whose type the caller cannot ignore. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Real-world TypeScript
- 4 tasks
- TypeScript
- In the all labs plan
The first 2 chapters of TypeScript for real code are free. This one comes with the all labs plan.
Why you need this
When the UPI gateway goes down, Tapri's app shows customers an empty red box. Anjali wants a real sentence in it. Kabir found the cause: the gateway's library throws plain strings, not errors, and Bunty's catch block reads err.message from whatever arrives. A string has no message, so the box gets undefined.
With catch (err: any) TypeScript checks nothing, so that bug compiles. And when a function fails in an expected way (a customer types "two" for the number of cups), a throw is invisible: nothing in the function's type tells the caller to handle it, so most callers forget.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
messageOf: a sentence from anything that was caught
messageOf(err) turns whatever a catch got into text for the screen. An Error gives its message, a string is used as it is, and anything else gives 'Something went wrong': messageOf(new Error('UPI timed out')) is 'UPI timed out', messageOf('rider not found') is 'rider not found', and messageOf(42), messageOf(null) and messageOf(undefined) are 'Something went wrong'.
Its parameter must be exactly unknown instead of any, because a catch can hold anything at all, and it returns a string.
- Task 2
OutOfStockError: an error that knows which item ran out
new OutOfStockError('ginger') is an Error (instanceof Error is true) with the message 'ginger is out of stock', the name 'OutOfStockError' and a field item that holds 'ginger'. item is a readonly string, so changing it afterwards is a type error, and so is new OutOfStockError(5). Declare the field in the class body and set it in the constructor: a constructor parameter property does not run in node.
explainFailure(err) takes exactly unknown and returns a string: 'Sorry, ginger is out of stock today' for an OutOfStockError, and what messageOf gives for anything else (an Error's message, a string as it is).
- Task 3
parseQty: a Result instead of a throw
Write Result<T, E> instead of any: either { ok: true; value: T } or { ok: false; error: E }, with E being string when it is left out. Then reading value before checking ok is a type error, and so are { ok: false, value: 2 } and { ok: true, error: 'no' }.
parseQty(text) reads how many cups were ordered and returns a Result<number> without ever throwing. parseQty('2') is exactly { ok: true, value: 2 } and parseQty('20') is { ok: true, value: 20 }. parseQty('two'), parseQty('2.5') and parseQty('') fail, and so do parseQty('0') and parseQty('21'), because a quantity is a whole number from 1 to 20. A failure is { ok: false, error: <a short message, as text> }.
- Task 4 · interview question
Interview: attempt, any throw turned into a Result
attempt(fn) calls fn and never throws. If fn returns, it gives { ok: true, value } with what fn returned: attempt(() => 42) is { ok: true, value: 42 }. If fn throws, it gives { ok: false, error }, and the error is always an Error: if fn threw an Error (an OutOfStockError, say), it is that same object; if it threw something else, like the string 'oops', it is new Error('oops').
Make it generic with no any left: it takes a function with no parameters, so attempt(42) is a type error, and returns a Result<T, Error> where T is what that function returns, so attempt(() => ['masala chai']) holds a string[]. Dev will ask why the error is wrapped, and where the type of value comes from.
What you will learn
- unknown in catch: anything can be thrown, so a caught value must be checked before it is used.
- Error classes: a subclass of Error that carries typed data, found again with instanceof.
- Result types: a union that puts success and failure into the return type, told apart by a true or false tag.
More in Real-world TypeScript
Build "When things go wrong" yourself
Tapri’s codebase grows, and types keep it honest. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of TypeScript for real code are free. This one comes with the all labs plan.