Types You Don't Control 12 exercises
solution

Update tsconfig.json to include DOM typings

Similar to what we've done previously, we need to update the tsconfig.json file to include DOM in the lib section:


{
"compilerOptions": {
"target": "ES2022",
"lib": [
"ES2022",
"DOM",
]
...

Once the DOM option has been added, TypeScript will be ab

Loading solution

Transcript

00:00 Okay, so the solution here is to look at our tsconfig.json. In our tsconfig.json, we have target specified, that's good, but we also have lib specified. And we have lib specified to just ES 2022. Now, if I open up the other file here, index.ts,

00:18 let's open this out so it's, let me grab the tsconfig so we're looking at both at the same time. Now, what happens here if I delete lib? Let's see what happens then. I delete it, and now inside index.ts, it's actually going to add the DOM types for me automatically.

00:38 That's because the default value for lib is actually based on the target. So if you have target set to ES 2022, it's going to include lib, and it's also going to include the DOM typings as well. But if we want to add those manually, we can say lib ES 2022, and then we add DOM.

00:58 And now we get the typing. So if I remove DOM, let's do that, and we see index.ts takes a minute to just catch up, and we get document inside here. Cannot find document. Do you need to change your target library? Try changing the lib compiler option to include DOM. Bam, there we go. And I'm pretty sure it can be lowercase or uppercase, doesn't matter.

01:17 I like uppercase because that's what it autocompletes to. But let's take a look at document then. So let me just change that, and I'm going to command click on documents here, and I go to a file called lib.dom.d.ts, which is inside the global typings for TypeScript. And lib.dom.d.ts,

01:36 this has references to all of the stuff we're talking about. So here is document. Here is a bunch of other stuff too, all of the ad event listener stuff. This file is thousands of lines long, if I remember correctly. I don't have line numbers on, but good Lord, look at this. The DOM is very, very big, and you get all of it all at once. It's pretty hard to be like,

01:55 God, it's still going, isn't it? It's pretty hard to break it down into smaller chunks because people don't use the DOM like that. You're either in the DOM or you're not. So lib.dom.d.ts is very, very useful because it exposes a bunch of global types that help you interact with the DOM, and it's critical to include for any web application.