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 is giving us an error on e.message
that the object is of type unknown
.
Challenge
Your challenge is to coerce the unknown
type into one where we know what it is.
Hint: there are a few ways to solve this challenge-- see what you can come up with!
Transcript
The problem with this exercise is that we're testing a tryCatch. I've mocked up this situation where we can make the tryCatch fail when we want to. If we have state === "fail" here, then we throw the error.
We're getting this error here because object is of type 'unknown'. That's because anything that you catch inside an error here, inside a catch block, is going to be unknown.
We need to somehow coerce this unknown to be the type that we want it to be, that we know it is. It's going to be an error here. We somehow need to extract the message from that error.