When dealing with exceptions in TypeScript, it’s common to see something like this:
try {
// Desired logic.
} catch (e) {
console.error(e.message); // This can cause an error!
}
By default, TypeScript assumes that (e) is of type any. However, common errors such as 403, 404, 500, 504, and many others can trigger exceptions, and they don’t always share the same response structure. This can lead to runtime issues if you try to handle the error in a user-friendly way without properly validating its type.
Why Use unknown ?
The unknown type was introduced as a safer alternative to any. It prevents us from performing direct operations on a variable without first verifying its type, forcing us to handle errors correctly before accessing any properties.
Correct Error Handling Example:
try {
// Desired logic.
} catch (e: unknown) {
if (e instanceof Error) {
console.error(e.message); // Now it's safe to access .message
} else {
console.error("Unknown error:", e);
}
}
With this approach, we prevent unknown errors from breaking our application and ensure that unexpected issues don’t escape our control or get directly exposed to the end user.
Top comments (0)