TypeScript ยท Chapter 42 of 44

TypeScript Error Handling

Error handling in TypeScript uses the same try/catch/finally structure as JavaScript, but you need to be careful with types since caught errors are typed as `unknown` by default in strict mode.

Because the type of a caught error isn't guaranteed to be an `Error` object, it's good practice to check its type before accessing properties like `.message`, keeping your error handling both safe and informative.

Syntax
try {
  // risky code
} catch (error: unknown) {
  if (error instanceof Error) {
    console.log(error.message);
  }
}

try/catch with types

Inside a catch block, the caught value has type `unknown` under strict settings, so you should narrow it (for example with `instanceof Error`) before using error-specific properties.

Custom error classes

You can create custom error types by extending the built-in Error class, adding extra properties or a distinct name to represent specific kinds of failures in your application.

Example 1 (typescript)
try {
  throw new Error("Something went wrong");
} catch (error: unknown) {
  if (error instanceof Error) {
    console.log(error.message);
  }
}
Output
Something went wrong

instanceof Error narrows the unknown caught value so .message can be accessed safely.

Example 2 (typescript)
class ValidationError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "ValidationError";
  }
}
try {
  throw new ValidationError("Invalid input");
} catch (error: unknown) {
  if (error instanceof ValidationError) {
    console.log(`${error.name}: ${error.message}`);
  }
}
Output
ValidationError: Invalid input

A custom error class lets you distinguish specific error types with instanceof checks.

Key points

  • Caught errors are typed as unknown under strict settings.
  • Use instanceof Error to safely narrow a caught error before accessing its properties.
  • Custom error classes can extend the built-in Error class.
  • Good error handling keeps both runtime safety and type safety.
๐Ÿ’ก Note: Always narrow unknown errors before accessing properties โ€” assuming an error is always an Error instance can cause runtime crashes.

๐Ÿ“ Quick Quiz

1. What type is a caught error under strict TypeScript settings?

2. How do you safely access .message on a caught error?

3. How do you create a custom error type?