unknown in Error Handling
You'll learn: How to type caught errors as unknown since JavaScript can throw anything, then safely narrow them to the types you need.
The Weird Truth About JavaScript Errors
In JavaScript, the catch clause can receive literally anything. Someone can throw "oops", throw 42, throw null, or even throw { randomObject: true }. Most of the time you catch actual Error objects, but TypeScript can't assume that.
Before TypeScript 4.0, caught errors were typed as any, which meant you lost all type safety. Modern TypeScript (4.0+) types them as unknown instead, forcing you to verify what you actually caught before using it.
Why unknown Is Perfect Here
Think of catch (e) like receiving a mystery box from an external system. You don't know what's inside until you check. That's exactly what unknown represents: "I have a value, but I don't know its type yet."
try {
riskyOperation();
} catch (e) {
// e is unknown — can't use it directly
console.log(e.message); // ❌ Error: Object is of type 'unknown'
}
Narrowing to Error
The most common pattern is checking if the caught value is actually an Error:
try {
riskyOperation();
} catch (e) {
if (e instanceof Error) {
console.log(e.message); // ✅ Safe: TypeScript knows it's Error
console.log(e.stack);
} else {
console.log("Something weird was thrown:", e);
}
}
Handling Non-Error Throws
You might also need to handle strings or other types that poorly-written code might throw:
try {
someLibrary();
} catch (e) {
if (e instanceof Error) {
return { success: false, message: e.message };
} else if (typeof e === "string") {
return { success: false, message: e };
} else {
return { success: false, message: "Unknown error occurred" };
}
}
Key Takeaway: Always type caught errors as unknown and narrow them with instanceof Error or other type guards — JavaScript can throw anything, so TypeScript makes you check what you actually caught.