Unions and Narrowing 28 exercises
solution

Throwing Errors to Narrow

In order to crash the app if appElement does not exist, we can add an if statement that checks if appElement is null or does not exist, then throws an error:

if (!appElement) {
  throw new Error("Could not find app element");
} 

By adding this error condition, we can be sure th

Loading solution

Transcript

00:00 Okay, the solution I was hinting at here is that we actually want to throw an error if app element does not exist. So we've added an if statement saying, if there's no app element or if app element basically is null, throw an error because inside this scope here, app element is null.

00:19 And then you'll notice that after that, if we think of this as like an execution sequence, right? You run this first line of code. It could be null or it could be HTML elements. Then we hit this line of code. And if there's no app element, so it being null, we throw an error.

00:36 This means that we can never get to this line of code here. Let's say we just console.log the app element. We can never get to this line of code with it being null. That's just not possible. So this means that by throwing errors in these types of situations, we can just like narrow code for us in TypeScript.

00:54 So this almost acts like a type annotation because we probably know that, you know, if we're running like a VTAP or something like that, then the app elements that our entire app relies on, we might be rendering into that div, for instance. That's probably gonna be there, right? That'd be pretty bad if that wasn't there.

01:13 But just by having this extra little elements here, it means that if it, for some reason, isn't there, we'll get a proper runtime crash, which tells us what's going on and alerts us pretty quickly. And it means that our TypeScript types are playing nicely. But anyway, this gives you a really nice way to sort of narrow down certain pieces of logic

01:32 in certain moments. And yeah, like throwing errors to narrow is a really, really good concept for, really, if you want to just manage any kind of logical flow throughout your apps.