Error Handling with unknown
What you'll learn: How catch clauses in TypeScript receive unknown instead of any, and why you must narrow before accessing error properties.
The Default Error Type in Modern TypeScript
In JavaScript, you can throw anything—a string, a number, an object, or even undefined. Because of this unpredictability, TypeScript 4.0+ changed how catch clauses work: the caught error is now typed as unknown by default (when useUnknownInCatchVariables is enabled or you're in strict mode).
This means you cannot immediately access .message or .stack on a caught error. TypeScript forces you to verify what you actually caught first.
Why This Matters
Before this change, errors were implicitly any, which meant no type checking:
try {
riskyOperation();
} catch (err) {
// Old behavior: err was 'any'
console.log(err.message); // No error, but unsafe!
}
Now with unknown:
try {
riskyOperation();
} catch (err) {
// err is 'unknown'
console.log(err.message); // ❌ Error: Property 'message' does not exist
}
Narrowing the Error Type
You must narrow unknown to a specific type before using it. The most common pattern checks if it's an Error instance:
try {
riskyOperation();
} catch (err) {
if (err instanceof Error) {
// Now TypeScript knows it's an Error
console.log(err.message);
console.log(err.stack);
} else {
// Handle non-Error throws
console.log("Something unexpected was thrown:", err);
}
}
You can also check for specific error types, null, or strings:
try {
somethingElse();
} catch (err) {
if (typeof err === "string") {
console.log("String error:", err);
} else if (err instanceof Error) {
console.log("Error object:", err.message);
} else {
console.log("Unknown error type");
}
}
Key Takeaway: Catch clauses receive unknown in strict TypeScript, requiring you to narrow with instanceof Error or other type guards before safely accessing error properties—preventing runtime crashes from unexpected throw values.