Beginner's TypeScript Section 18 exercises
Problem

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 o

Loading exercise

Transcript

0:00 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.

0:14 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.

0:25 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.