Unions and Narrowing 28 exercises

Narrowing by Throwing Errors

Here we have a line of code that uses document.getElementById to fetch an HTML element, which can return either an HTMLElement or null:

const appElement = document.getElementById("app");

Currently, a test to see if the appElement is an HTMLElement fails:

Loading exercise


00:00 In this exercise, we have some code which is doing a document.getElementById app. And what this returns is a HTML element or null. So, what we want to do is to make sure that app element is always defined.

00:15 And we actually want to really, at runtime, make sure that element is defined. We could kind of lie to TypeScript using some techniques I'll show you in a bit, but we don't really want to lie to TypeScript. We want to make sure that by the time we're doing something to that element, for instance, let's say, by this line of code down here,

00:34 we want to make sure that it's definitely not null. And I'm going to leave it to you how we do that. You're going to be surprised by TypeScript's inference, I think, here. We actually want to, let's say, actually, we want to crash our app if app element is null.

00:53 We actually just want to crash. Let's say that, and let's see how TypeScript handles that information.