← Back to TypeScript Course | Chapter 18: Error Handling | Lesson 1 of 5

try/catch with Types

TypeScript uses JavaScript's try/catch mechanism, but caught errors should be treated safely because their type is not known automatically. Using unknown and narrowing with instanceof helps write reliable error-handling code.

Basic try/catch

A try block contains code that may fail, while the catch block handles whatever exception gets thrown — in TypeScript, the caught value is typed as unknown by default rather than any, which forces you to check it before use.

Example: Basic try/catch

typescript
try {
  throw new Error("Something broke");
} catch (err: unknown) {
  console.log(typeof err);
}

Narrowing an Error

An unknown caught value should be narrowed — with instanceof Error, for example — before accessing properties like message, since TypeScript won't let you read properties off an unknown value without first proving what shape it has.

Example: Narrowing an Error

typescript
try {
  throw new Error("Failed");
} catch (err: unknown) {
  if (err instanceof Error) {
    console.log(err.message);
  }
}

Handling Unknown Thrown Values

JavaScript allows literally anything to be thrown, not just Error objects, so TypeScript code should never assume a caught value is an Error without checking — a thrown string or plain object is completely legal JavaScript.

Example: Handling Unknown Thrown Values

typescript
try {
  throw "just a string";
} catch (err: unknown) {
  if (typeof err === "string") {
    console.log("String thrown:", err);
  } else if (err instanceof Error) {
    console.log("Error thrown:", err.message);
  }
}

Typed Error Handling Helpers

A small helper function can centralize the logic for turning any caught value into a readable message, keeping the narrowing boilerplate in one place instead of repeated at every catch block in the app.

Example: Typed Error Handling Helpers

typescript
function toMessage(err: unknown): string {
  if (err instanceof Error) return err.message;
  if (typeof err === "string") return err;
  return "Unknown error";
}
try {
  throw new Error("Oops");
} catch (err) {
  console.log(toMessage(err));
}

Best Practices

Treat caught values as unknown, narrow them before use, and always provide a sensible fallback message for the case where the thrown value isn't a standard Error — this keeps error handling predictable even with badly-behaved third-party code.

Example: Best Practices

typescript
function toMessage(err: unknown): string {
  return err instanceof Error ? err.message : "Something went wrong";
}
try {
  throw { weird: "object" };
} catch (err) {
  console.log(toMessage(err));
}
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.