useUnknownInCatchVariables: Safer Error Handling
What you'll learn: Why TypeScript now defaults catch variables to unknown instead of any, forcing you to validate errors before using them.
The Problem with Traditional Error Handling
Historically, when you caught an error in JavaScript (and older TypeScript), the caught variable was typed as any:
try {
somethingRisky();
} catch (error) {
// In old TypeScript: error is 'any'
console.log(error.message); // No type checking!
error.someRandomMethod(); // TypeScript won't complain
}
This is dangerous because anything can be thrown in JavaScript—not just Error objects. Someone could throw "a string", throw 42, or throw null. The any type gives you a false sense of security.
The useUnknownInCatchVariables Solution
When you enable useUnknownInCatchVariables (included automatically with strict: true), catch variables become unknown instead:
try {
somethingRisky();
} catch (error) {
// error is now 'unknown'
console.log(error.message); // ❌ Error: Property 'message' doesn't exist on 'unknown'
// You MUST narrow the type first
if (error instanceof Error) {
console.log(error.message); // ✅ Safe!
}
}
This forces you to prove what you caught before accessing properties, preventing runtime crashes from assumptions.
Why This Matters
Think of unknown in catch blocks like a mystery package at your door. The any approach is like assuming it's always a pizza box and trying to eat whatever's inside. The unknown approach makes you open it and check first—it might be pizza, might be socks, might be empty!
Key Takeaway: useUnknownInCatchVariables makes error handling safer by typing catch variables as unknown, requiring you to validate errors with type guards before accessing their properties.