0Pricing
TypeScript Academy · Lesson

Narrowing Caught Errors (unknown vs Error)

Safely handle caught errors typed as unknown.

Narrowing Caught Errors (unknown vs Error) is a free TypeScript Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Welcome

Since TypeScript 4.0, caught errors are unknown. This forces explicit narrowing before using error properties.

TS 4.0 Change

TypeScript 4.0 introduced useUnknownInCatchVariables. Caught errors are unknown in strict mode.
// err is now: unknown
try { doSomething(); }
catch (err) {
  // err.message; // Error — cannot access on unknown
}

instanceof Narrowing

Use instanceof Error to safely access error properties.
catch (err) {
  if (err instanceof Error) {
    console.error(err.message, err.stack);
  } else {
    console.error('Unknown error:', String(err));
  }
}

isError Type Guard

Create a reusable type guard for error narrowing.
function isError(e: unknown): e is Error {
  return e instanceof Error;
}
catch (e) {
  if (isError(e)) console.error(e.message);
}

Custom Error Narrowing

Narrow to custom error types in catch blocks.
catch (err) {
  if (err instanceof NetworkError) { /* retry */ }
  else if (err instanceof AuthError) { /* redirect */ }
  else if (err instanceof Error) { /* generic */ }
  else throw err;
}

useUnknownInCatchVariables

This flag (part of strict in TS 4.4+) enforces unknown for caught errors.
{ "compilerOptions": { "useUnknownInCatchVariables": true } }

String Errors

Some code throws strings instead of Error objects. Handle both.
catch (err) {
  const message = err instanceof Error ? err.message : String(err);
  console.error(message);
}

Typed throw Helper

Create a helper that always throws a typed Error.
function throwErr(msg: string, code = 500): never {
  const e: AppError = Object.assign(new Error(msg), { statusCode: code });
  throw e;
}

Re-throwing Unknown Errors

Re-throw errors you cannot handle.
catch (err) {
  if (err instanceof KnownError) handle(err);
  else throw err; // propagate unknowns
}

Error Boundaries in React

React error boundaries must handle unknown errors from lifecycle methods.
componentDidCatch(error: unknown, info: ErrorInfo) {
  if (error instanceof Error) logError(error.message);
}

Testing Caught Errors

Test error handling with typed assertions.
test('catches errors', async () => {
  jest.spyOn(api, 'fetch').mockRejectedValue(new NetworkError());
  const result = await safeRun();
  expect(result.ok).toBe(false);
});

Quick Check

What is the type of a caught error `err` in TypeScript 4.4+ strict mode?

Recap

Narrowing Caught Errors (unknown vs Error): you learned the key concepts of this topic and how to apply them in real TypeScript projects.

Frequently asked questions

Is the “Narrowing Caught Errors (unknown vs Error)” lesson free?

Yes — the full text of “Narrowing Caught Errors (unknown vs Error)” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Narrowing Caught Errors (unknown vs Error)”?

Safely handle caught errors typed as unknown. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start TypeScript Academy?

No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Narrowing Caught Errors (unknown vs Error)” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this TypeScript Academy lesson?

Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Typed Error Classes and Hierarchies
  2. The Result Pattern: Ok and Err
  3. Narrowing Caught Errors (unknown vs Error)
  4. Error Handling in Async TypeScript Code
← Back to TypeScript Academy