ReviseAlgo Logo

Error Handling & Patterns

Typing Error Objects

Safely type unknown catch block errors in TypeScript.

Last Updated: July 29, 2026 10 min read

In TypeScript catch clauses, errors are implicitly typed as unknown (under useUnknownInCatchVariables). You must narrow errors before accessing properties like error.message.

1. Introduction & Architecture

2. Deep Dive & Core Concepts

Because any JavaScript expression can be thrown (throw "string" or throw 404), TypeScript forces catch block variables to be unknown for runtime safety.

3. Basic Code Example

4. Advanced Production Patterns

5. Interactive Code Playground

function parseJSON(input: string) {
  try {
    return JSON.parse(input);
  } catch (err: unknown) {
    if (err instanceof SyntaxError) {
      console.log("JSON Syntax Error:", err.message);
    }
  }
}
parseJSON("{ bad json }");

6. Common Pitfalls & Edge Cases

Note: Do NOT cast catch variables directly as catch (error: any) because this turns off type checking and hides unhandled non-Error throws.

7. Interview Q&A & Quizzes

Q: Why are catch variables in TypeScript typed as unknown rather than Error?

A: In JavaScript, anything (strings, numbers, objects) can be thrown via throw, so the type cannot be statically guaranteed to be an Error instance.

8. Summary Comparison Table

Catch TypeType SafetyInspection Requirement
unknown (Default)HighRequires instanceof Error type guard
| any | Zero | Dangerous direct property access |