DOM basics
These programs are page scripts: they run in a browser, and the lines under each one are what its console prints. A command-line Node program has no document, so the same file started there stops with ReferenceError: document is not defined.
querySelector typed
In the browser, TypeScript knows the page structure through built-in DOM types. querySelector takes a CSS selector and returns the matching element. Pass a generic to state which kind of element is expected, and the result carries the matching type. The page holds one heading:
<h1>Shop</h1>
const title = document.querySelector<HTMLHeadingElement>("h1"); console.log(title?.textContent);
Shop
The generic is the contract with the markup: h1 promises a heading element. Pick the generic that matches the tag, and autocompletion offers exactly the fields that tag owns. The program prints the text of that heading.
Narrow the null
The element may be missing, so the type always includes null. TypeScript blocks any use before the check, which turns a runtime crash into a compile-time reminder. Narrow with a plain if and throw early, and after that line the value is a real element. The page is the same one:
<h1>Shop</h1>
const title = document.querySelector<HTMLHeadingElement>("h1"); if (title === null) { throw new Error("missing h1"); } title.textContent = "Hello"; console.log(document.querySelector("h1")?.textContent);
Hello
The throw documents the assumption: this page must contain an h1. Readers of the code see the requirement instead of guessing it. The program sets the text and prints it back, so the output shows that the element was really there.
Change text
textContent sets plain text and stays safe with user data: tags inside the string show as text, never as markup. Wrap the read-and-check into a small function, and every title update follows the same safe path. The page still holds the heading:
<h1>Shop</h1>
function setTitle(text: string): void { const title = document.querySelector<HTMLHeadingElement>("h1"); if (title === null) { return; } title.textContent = text; } setTitle("Shop"); console.log(document.querySelector("h1")?.textContent);
Shop
Here a missing heading means quiet return instead of a crash, which fits optional page parts. Choose throw for required elements and return for optional ones. The program calls the function and prints the heading it changed.
Create elements
document.createElement builds a new node of a precise type, and appendChild places it on the page. Set the text before attaching, so readers never see a half-built element. The page holds an empty list:
<ul></ul>
const item: HTMLLIElement = document.createElement("li"); item.textContent = "Buy milk"; const list = document.querySelector<HTMLUListElement>("ul"); if (list === null) { throw new Error("missing ul"); } list.appendChild(item); console.log(list.children.length, document.querySelector("li")?.textContent);
1 Buy milk
createElement with the li tag returns HTMLLIElement directly, so no check is needed for the new node. Only the lookup of the existing list can fail, and the narrow handles that case. The program prints the number of rows and the text of the new one.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
querySelectorreturn when no element matches the selector?Answer
nullThe lookup gives
null, which is why the type of the result always includes it. -
What does the generic in
querySelector<HTMLHeadingElement>("h1")do?Answer
It states the element type, so the result carries that type
The generic is a promise about the markup: the compiler then offers the fields of a heading element.
-
Why check the result of a lookup for
nullbefore using it?Answer
Because a missing element would crash at run time
The element may not exist, and reading a field of
nullthrows at run time; the check turns that into a clear early failure. -
What does
textContent = "<b>Hi</b>"put on the page?Answer
The literal text
<b>Hi</b>textContentnever parses markup, so the tags show as text, which is what keeps user data safe. -
What does
document.createElement("li")return?Answer
HTMLLIElementThe tag map gives the precise type, so no check or cast is needed for a node the program just built.
-
What does the compiler say about this program?
const title = document.querySelector<HTMLHeadingElement>("h1")!; title.textContent = 1; console.log(title);Answer
error TS2322: Type 'number' is not assignable to type 'string'.
textContentis a string field, so a number is rejected even though the element itself is a heading. -
What does the compiler say about this program?
const list = document.querySelector<HTMLUListElement>("ul"); list.appendChild(document.createElement("li"));Answer
error TS18047: 'list' is possibly 'null'.
The lookup may give
null, and the compiler refuses to call a method on a value that may be missing. -
What does the compiler say about this program?
const title = document.querySelector<HTMLHeadingElement>("h1"); console.log(title.textContent);Answer
error TS18047: 'title' is possibly 'null'.
The check is missing, so the compiler stops at the use of a value that may be
null. -
What does this program print?
const tag: keyof HTMLElementTagNameMap = "li"; console.log(tag);Answer
li
The type of
tagis the string union of HTML tag names, and the value printed is that string. -
What does
appendChilddo with the node it receives?Answer
It adds the node as the last child of the element
The node joins the tree under the element, which is why setting its text before attaching it avoids a half-built row.
Article author: Arthur Isaev