Unions and Narrowing 28 exercises

Narrowing with `instanceof`

The way to solve this challenge is to narrow types using the instanceof operator.

Where we check the error message, we'll check if error is an instance of Error:

if (error instanceof Error) {

The instanceof operator covers all children th

Loading solution


00:00 Okay, let's try this first one. So my first idea here or at least the first thing I thought was to think of if message in error Then you can go for it. But this one you'll notice it's sort of a little bit It's a little bit hard to wrangle error is of type unknown. So in fact, we'd have to go something like if type of error

00:22 equals object and Do this except now error is typed as object or null. So we need to because of you know of that horrible bug in JavaScript that means that nulls are considered type of object

00:37 We probably need to also just check that it exists as well. And now finally, it's sort of understanding that error dot message is Something that it can cancel log but error message is still of type unknown here There is a a nicer way to handle this we can actually do if instance of

00:57 Error or sorry if error instance of error Boom everything's now working So it's using the instance of operator which compares whether this error Variable is an instance of and I'm pretty sure that works. Even if this was like a type error or something like that

01:17 Because this one inherits from the original error constructor So if it's an instance of the error constructor, then it checks it and it will console log the error So what this is something that you'll often do inside Try catches and what I tend to do is because we're not actually like handling all of the errors here

01:36 We're just handling the ones that we know are errors But if for instance someone like just through like a string like this, then this wouldn't actually catch this Boundary here. So what I like to do is just also say Else throw error and this means that you're covered both ways

01:53 So you're handling all of the errors, you know about but the ones that you don't know about which will always come up You know, we're always going to screw up as programmers They still get thrown and so they it doesn't just swallow the error and silently betray you So this is a really nice way using instance of that. You can narrow down unknown into known classes