What You'll Learn
You'll learn how enabling useUnknownInCatchVariables makes error handling safer by treating caught errors as unknown instead of any, forcing you to validate errors before using them.
The Default Problem
In JavaScript and TypeScript, when you catch an error, the variable in the catch clause has historically been typed as any:
try {
riskyOperation();
} catch (error) {
// error is 'any' by default
console.log(error.message); // No error, but unsafe!
}
This is dangerous because anything can be thrown in JavaScript—not just Error objects. Someone could throw a string, a number, or even null. The any type gives you a false sense of security.
What useUnknownInCatchVariables Does
When you enable this option in your tsconfig.json, catch clause variables become unknown instead of any:
{
"compilerOptions": {
"useUnknownInCatchVariables": true
}
}
Now TypeScript forces you to narrow the type before accessing properties:
try {
riskyOperation();
} catch (error) {
// error is now 'unknown'
// This causes an error:
// console.log(error.message);
// You must narrow first:
if (error instanceof Error) {
console.log(error.message); // Safe!
} else {
console.log('Unknown error:', error);
}
}
Think of It Like a Security Checkpoint
Imagine a catch block as a net that catches anything falling. The old any behavior is like assuming everything caught is a basketball. The unknown behavior is like admitting "we caught something—let's check what it is before we try to dribble it."
Real-World Pattern
function handleOperation() {
try {
dangerousTask();
} catch (error) {
if (error instanceof Error) {
logError(error.message);
} else if (typeof error === 'string') {
logError(error);
} else {
logError('An unexpected error occurred');
}
}
}
This pattern forces you to handle the reality that errors aren't always Error objects, making your error handling more robust.
Key Takeaway: useUnknownInCatchVariables treats catch variables as unknown instead of any, requiring you to validate errors before using them—preventing runtime crashes from unexpected thrown values.