Module lessons (1/3)
Error Handling with unknown and Type Guard on Error
Leverage useUnknownInCatchVariables, safely extract messages, and design typed Error hierarchies.
What you'll learn in this lesson
- Understand why in JavaScript you can cast any value (
throw 'oops', numbers,null) and whystricttypes the variables ofcatchasunknown. - Write reusable helpers to normalize exceptions (
toErrorMessage(err: unknown): string). - Correctly extend
Errorwith domain subclasses (settingthis.nameand preservingcausein ES2022). - Distinguish
instanceof Errorwith respect to duck typing between isolated frames or contexts.
Overview
In many languages you can only cast subclasses of an error base class. In JavaScript, however, throw 'Timeout!' or even throw 404 are valid at runtime! If the compiler assumed that every error caught was a Error, reading err.message would cause TypeError: Cannot read properties of undefined.
This is why from TypeScript 4.4 with strict: true useUnknownInCatchVariables is active: every catch (err) automatically assigns the type unknown to err.
Sections covered in this lesson
- 1Normalize
err: unknownin thecatchblock - 2Guided practice
- 3Check for understanding
Unlock "Error Handling with unknown and Type Guard on Error" and the full Course TypeScript curriculum
Leverage useUnknownInCatchVariables, safely extract messages, and design typed Error hierarchies.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course TypeScript plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.