Unions and Narrowing 28 exercises

Dealing with Unknown Errors in TypeScript

In TypeScript, one of the most common places you'll encounter the unknown type is when using a try...catch statement to handle potentially dangerous code. Let's consider an example:

const somethingDangerous = () => {
if (Math.random() > 0.5) {
throw new Error("Something wen

Loading exercise


00:00 One of the most common spots you're going to see unknown in TypeScript is in these situations where you're try catching over something dangerous, let's say. So let's say you've got some dangerous code here, and this is a something dangerous function, where on a 50-50 chance, it's going to throw an error saying something went wrong.

00:19 Otherwise, it's going to return all good. Down the bottom, we're try catching over that, and in our catch clause, we have an error, and the error is typed as unknown. Okay, that's a little bit strange. This is something that happens by default in TypeScript.

00:36 And what we want to do is we want to basically say, okay, when that error comes up, we want to console.error it. And we only, I think, want to do that if it contains a message attribute. So there is a really nice way you can do this.

00:51 So we kind of want to find some sort of if condition here to, we really want to change this condition to make sure that it's acting properly. And that's that we only throw an error if we know it has a message attribute, because we know that errors like come with a message attribute, like this.

01:10 Even this error here, if we just say like, const error equals this, it will have error.message that we can then read out to the console, for instance. So your job then is to try to find a way, try to find the right condition to do this. I'm gonna give you a clue.

01:24 It's not necessarily, I imagine you could probably do this with like error in error, for instance, or message in error. But I want you to think of the fact that error is a class. See if that gives you a hint. Good luck.