Beginner's TypeScript #13
Nhan Nguyen
Posted on January 1, 2024
⭐ Typing Errors in a Try-Catch ⭐
Take a look at this try-catch demo:
const tryCatchDemo = (state: "fail" | "succeed") => {
try {
if (state === "fail") {
throw new Error("Failure!");
}
} catch (e) {
return e.message;
}
};
TypeScript gives us an error on e.message that the object is of type unknown.
We will figure out how to coerce the unknown type into one where we know what it is.
🌟 Solutions:
We have several ways to solve this problem.
1️⃣ Use Any Type:
One way to solve this challenge is to type e in the catch as any:
} catch (e: any) {
return e.message;
}
We can use any because we are pretty confident that the error will be an error.
What makes this solution not ideal is that we lose autocomplete on the e. This makes it easy to end up with typos that can cause issues later.
This is not a good solution.
2️⃣ Coerce as Error:
A slightly better solution would be to coerce e to be an Error, and return the message:
} catch (e) {
return (e as Error).message;
}
Here e is still unknown when we enter the catch, but using as coerces it to an Error, and we get our autocomplete as expected.
This solution is about as unsafe as the one above - we are not checking if e is an Error. We are casting it as an error.
3️⃣ Check with instanceof:
This solution is pretty similar to the last, except this time we'll use instanceof to see if e is an Error:
} catch (e) {
if (e instanceof Error) {
return e.message;
}
}
Unlike previous solutions. This time we are checking e at runtime to whittle down what it could be.
We are not blanketing it with the any type, and we are also not casting it to something else either.
This is the best solution because it is the safest.
I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
Posted on January 1, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.