Skip to main content
Module 9 · Lesson 1 of 318/22 in the course~15 min
Module lessons (1/3)

Error Handling with unknown and Type Guard on Error

Lesson preview5 hands-on exercises readyCourse TypeScript · Module 9 — Error Handling, Result Pattern & Architecture

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 why strict types the variables of catch as unknown.
  • Write reusable helpers to normalize exceptions (toErrorMessage(err: unknown): string).
  • Correctly extend Error with domain subclasses (setting this.name and preserving cause in ES2022).
  • Distinguish instanceof Error with 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

  1. 1Normalize err: unknown in the catch block
  2. 2Guided practice
  3. 3Check for understanding
Pro Lesson · Module 9 — Error Handling, Result Pattern & Architecture

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.