In the browser: DOM types, the lib setting, and why querySelector can return null
TaskKit moves into a browser tab. Learn what the DOM is, how the lib setting tells TypeScript where code runs, why querySelector returns Element | null, and how to turn it into the element you need, with the page running right under the code.
TypeScript
Types
In the browser: DOM types, the `lib` setting, and why `querySelector` can return `null`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
TaskKit has lived in your terminal since Level 1. A friend who
never opens a terminal asks for it in a browser tab: a box to
type a task in, an Add button, the list under it. You open
TaskKit's folder, make a file main.ts, and write the line that
finds the Add button, document.querySelector("#add").
npm run check says nothing is wrong. Running the file stops on
that very line with ReferenceError: document is not defined.
Both tools did their job. The check believed the code would run
in a browser, and Node, which is not a browser, had no document
to give. In this lesson you learn what a web page looks like to
your code, how TypeScript knows which place your code runs in,
and why the one line that finds a button hands you something
that may be null. By the end, TaskKit's page adds tasks, and
every element it uses is checked before it is used.
A page is a tree of objects
A web page starts as a text file of HTML (HyperText
Markup Language): tags in angle brackets that say what is on the
page. <h1> is a heading, <input> a box to type in, <button>
a button, <ul> a list. An id gives one tag a name of its own,
so code can ask for exactly that one.
The browser does not keep that text. It reads it once and builds
an object for every tag, nested the way the tags are: the
DOM, short for Document Object Model. It adds two tags of its
own, an <html> around everything and a <body> around the
visible tags (the figure leaves <html> out). Each of those
objects is an element, and the whole tree hangs from one
object your code can always reach: document.
<h1>HTMLHeadingElement
<inputid="new-task">HTMLInputElement
<buttonid="add">HTMLButtonElement
<ulid="tasks">HTMLUListElement
<body>HTMLBodyElement
documentDocument
The browser builds an object for every tag, and lib's dom
names each one's type
Every element has a type, the way every value in TaskKit had
one. A button is an HTMLButtonElement, with disabled and
click(). A text box is an HTMLInputElement, with the value
the reader typed. The types are what let TypeScript tell a
button from a box, and a setting called lib decides whether
TypeScript has them at all.
Where these types come from: lib
TypeScript knows Array, Map and JSON without an import
because it loads descriptions of them that ship with it. Which of
those descriptions it loads is the lib setting in
tsconfig.json. "es2023" is JavaScript's own built-ins as of
its 2023 edition (ES is short for ECMAScript, the language's
official name), and "dom" adds the browser's document and
every element type. Level 2's tsconfig.json in detail:
target, module, rootDir, outDir, lib, types goes
through every value; one line of it is enough here.
TaskKit's tsconfig.json from Level 1 sets no lib at all.
Without one, TypeScript loads the language and the browser's
descriptions, so document passed the check in a project that
only ever runs in Node. That is the surprise from the start of
the lesson, and it has a one-line fix: say where the code runs.
Here is TaskKit's file with that line added at the top:
Now the same line is stopped by the check instead of by Node.
npm run check prints its two > lines, and then this; the
first line is one long line in your terminal, broken here to fit:
What the check printstext
main.ts:1:16 - error TS2584: Cannot find name 'document'. Do youneed to change your target library? Try changing the 'lib'compiler option to include 'dom'.1 const button = document.querySelector("#add"); ~~~~~~~~Found 1 error in main.ts:1
A project whose code runs in a browser lists the browser too:
"lib": ["es2023", "dom"]. Older projects also list
"dom.iterable", the part that lets for...of walk a list of
elements; since TypeScript 6 it is part of "dom".
lib holdsNodeA browseres2023
Right
document is unknown, as in Node: TS2584 catches it.
Toostrict
Page code fails the check: no document to find.
es2023, dom
Wrong,quietly
The check passes, then Node stops: it has no document.
Right
document, every element type, and the check holds.
The code runs in
lib should describe the place the code runs
You will rarely write that line for a browser project by hand.
The tools in Bundlers and dev servers (Vite) start a project
with it already in place; knowing what it means is what lets you
read an error like TS2584 and know which setting to look at.
Why querySelector can return null
document.querySelector takes a selector, a short pattern
that names elements: "#add" is the element whose id is add
(the # means id), "button" every button, "li" every list
item. It returns the first element that matches, or null when
none does.
TypeScript checks your .ts file. It never reads the HTML, which
is a different file, written by someone else, possibly changed
tomorrow. So it cannot know whether the page has an element with
id="add", and the type keeps both answers open: Element | null.
A typo, in the page or in the selector, gives the null road.
The figure walks this code:
ts
const button = document.querySelector("#add");if (button === null) { console.log("No Add button on this page.");} else { console.log("Add is ready.");}
Press Next step to walk the two roads, or let it play.
TypeScript cannot see the page, so the type keeps both roads open
All 3 steps shown.Step 1 of 3: button === null is trueStep 2 of 3: The block runs: No Add button on this page.Step 3 of 3: The next line
All 3 steps shown.
That is the narrowing you know from Level 1: check for null
once, and below the check the value is the element. Here is
TaskKit's page, wired up. <p> is a paragraph, <span> marks
a piece of it, here the count, and the tag's placeholder (not
the ${} placeholder of a template string) is the grey hint in
an empty box. The first line names the element's type in angle
brackets; the next section says why. Press Run, type a task
in the page under the code, and press its Add button.
addEventListener("click", …) hands the button a function to
call on every click, a callback like the ones from Level 1.
document.createElement("li") makes a new list item, and
textContent is the text inside an element: give it a string and
that becomes the text. list.append(item) puts the item at the
end of the list, so it shows on the page, and list.children
holds the elements inside the list, so its length is the number
of tasks.
Press Edit, change "#add" to "#ad" and run it again: the
page has no such element, the if catches it before anything
else runs, and the output says
TaskKit's page is missing an element.
From Element to HTMLInputElement
The first line above asks for querySelector<HTMLInputElement>.
Without the type argument in angle brackets (lesson 10.1),
input.value does not pass the check. Run this against the same
page:
The check answers
Property 'value' does not exist on type 'Element'. (TS2339).
An id says nothing about what kind of tag it belongs to, so
"#new-task" gives the plainest element type, Element, which
every tag has and which has no value. There are three ways to
get a more precise one:
Does: Checked on the page, every time the code runs
Never: Never treats another tag as an input
Only one of the three looks at the page when the code runs
The type argument is the same kind of promise as a type written on
a web API's answer in lesson 12.5 (API, application programming
interface, a website that answers programs with data): nothing
checks it, and the code only finds out when it breaks.
instanceof is the one that asks the page, so if the page
changes, the code takes the other road instead of breaking. Use
the type argument when the HTML is yours and sits beside the code,
as TaskKit's does; reach for instanceof when it is not, or when
a wrong guess would cost more than one line of checking.
Predict before you run
Predict
What type does TypeScript give item?
ts
const item = document.querySelector("li");
The common mistake: ! instead of a check
Writing the null check every time feels like extra work, and
TypeScript has a shortcut: a ! after a value, as in
document.querySelector("#add")!, the non-null assertion,
tells the check "this is not null", and the check takes null
out of the type without looking. On a page, it removes the check
and keeps the risk.
The check passes, because ! says the element is there. The page
has id="add", the code asks for "#ad", and the first line that
uses the button stops the page's script.
TypeError: Cannot read properties of null (reading 'addEventListener')
The fix
Keep the null and check it. TypeScript then makes you say what
happens when the element is missing, and the typo shows up as a
clear line instead of a crash.
The words above are Chrome's. Firefox says
can't access property "addEventListener", button is null, and
Safari null is not an object (evaluating 'button.addEventListener').
Whatever the words, an error that mentions null and a property
on a page means the same thing: look at the selector, then at the
HTML.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each exercise is checked in your browser. The two with a page run
your code against it: press Run to try the page yourself, and
Check when you think it works.
Exercise · Predict the result
Predict the type of an id
What type does TypeScript give save?
ts
const save = document.querySelector("#save");
Exercise · Fix the error
Make Add count the tasks
This page should add the typed task to the list and show how many
tasks there are. TypeScript refuses the code. Fix it so the checks
pass, without ! and without naming the type yourself in angle
brackets: let the page be checked.
A browser project's tsconfig.json has "lib": ["es2023"], and
npm run check stops on its first document with TS2584. Which
change fixes it?
Recap
Recap · 3 questions
Check yourself
What does the lib setting decide?
Check yourself
Why is querySelector typed Element | null?
Check yourself
Which of these checks the page when the code runs?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
In the browser: DOM types, lib and null
What things are
Word
What it means
HTML
The text of a page: tags in angle brackets
DOM
The tree of objects the browser builds from it
Element
One object of the tree: a button, a box, a list
document
The root of the tree, always there in a page
Selector
A pattern for finding one: #add, button, li
lib
The built-in descriptions the check loads
Code
Write
To
"lib": ["es2023"]
Check code that runs in Node
["es2023", "dom"]
Check code that runs in a browser
querySelector("#add")
Find by id: Element | null
querySelector("input")
Find by tag: HTMLInputElement | null
querySelector<T>("#id")
Say the type yourself; nothing checks it
instanceof
Check an element's type on the page
addEventListener
Call a function on every click
createElement("li")
Make a new list item
list.append(item)
Put it at the end of the list
textContent
The text inside an element
list.children
The elements inside the list
How it runs
Rule
What it means
Check for null
A selector may match nothing
No ! on a page
A typo crashes the page instead of failing the check
lib matches the place
Node without dom, a browser with it
Where to go next
You can now find any element on a page, say what TypeScript
should believe about it, check what it cannot know, and make the
page answer a click. That is all TypeScript in the browser rests
on: the DOM, its types, and null handled once.
Next is UI frameworks: what they are and why they exist. React
as an example (typed props and state in a few lines), with Vue,
Angular, and Svelte mentioned, where the page you just wired by
hand is written as components instead, and React keeps the list
and the count matching what you add.
Before you move on, press Edit on TaskKit's main.ts above
and make Add ignore an empty box, so pressing it with nothing
typed adds no task. Predict what the count shows after you press
Add twice on an empty box, then run it.