Course contentsShow
← TypeScript
Lesson 1218 of 1,79628. tsconfig in DepthFree lesson

useUnknownInCatchVariables: Typing Error Objects

Treat catch clause variables as unknown instead of any, forcing type validation before use.

useUnknownInCatchVariables: Typing Error Objects

What you'll learn: How to force TypeScript to treat error objects in catch blocks as unknown instead of any, making error handling type-safe.

The Default Behavior Problem

By default, when you write a catch clause in TypeScript, the error variable has the type any:

try {
  riskyOperation();
} catch (error) {
  // error is implicitly 'any'
  error.message; // No type checking - dangerous!
  error.anything; // Also allowed - yikes!
}

This any type means you can access any property or method without TypeScript complaining, even if the error doesn't actually have those properties. This defeats the purpose of type safety exactly where you need it most: error handling.

Enabling useUnknownInCatchVariables

When you enable useUnknownInCatchVariables in your tsconfig.json, TypeScript treats catch clause variables as unknown instead of any:

// tsconfig.json
{
  "compilerOptions": {
    "useUnknownInCatchVariables": true
  }
}

Now TypeScript forces you to validate the error before using it:

try {
  riskyOperation();
} catch (error) {
  // error is now 'unknown'
  // error.message; // ❌ Error: Object is of type 'unknown'
  
  // You must narrow the type first
  if (error instanceof Error) {
    console.log(error.message); // ✅ Safe!
  }
}

Why This Matters

Not everything thrown in JavaScript is an Error object. You can literally throw anything:

throw "a string";
throw 42;
throw { custom: "object" };
throw null;

By treating caught values as unknown, TypeScript forces you to handle all possibilities safely, exactly like when working with external data from APIs.

Key Takeaway: useUnknownInCatchVariables makes error handling type-safe by treating catch clause variables as unknown, forcing you to validate error types before accessing their properties—protecting against the reality that anything can be thrown in JavaScript.