Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 96 ยท TypeScript in Practice

TypeScript in the Browser (DOM)

Use TypeScript with the DOM - enable lib dom, handle querySelector's Element | null, narrow to HTMLInputElement, type event listeners and fetch responses safely.

TypeScript was born to make large browser applications manageable, and the browser APIs are where its types pay off fastest. Every element, event and Web API comes with a detailed type, so your editor knows that an <input> has a value, that a keydown event has a key, and that querySelector might find nothing at all.

That last point is the heart of this lesson. Browser code is full of things that might not exist: an element that isn't on the page, an event target that isn't the element you expected, a server response that doesn't have the shape you hoped for. TypeScript makes each of those possibilities visible, and you'll learn the patterns for handling them cleanly.

Our editor runs TypeScript on Node.js with "lib": ["esnext"], so document, window and HTMLElement don't exist there. Real DOM code in this lesson is shown read-only. The runnable examples use small hand-written interfaces shaped like the DOM types, so you can experiment with exactly the same typing techniques. The fetch examples are real, because Node 24 has fetch and Response built in.

Turning on the DOM types

The DOM types live in a library file called lib.dom.d.ts, which ships with TypeScript. Which libraries a project gets depends on the lib option in tsconfig.json (see tsconfig):

JSON
{
  "compilerOptions": {
    "target": "es2024",
    "lib": ["es2024", "dom", "dom.iterable"],
    "module": "esnext",
    "moduleResolution": "bundler",
    "strict": true,
    "noEmit": true
  }
}
  • "dom" declares document, window, every element interface (HTMLInputElement, HTMLButtonElement, ...), events, fetch, localStorage and the rest of the Web APIs.
  • "dom.iterable" lets you use for...of on collections like NodeList.
  • If you leave lib out entirely, TypeScript picks defaults based on target, including the DOM. Many projects set it explicitly so that Node code doesn't accidentally see browser globals, and browser code doesn't see Node's.

With a bundler such as Vite, noEmit is typical: TypeScript only type-checks, and the bundler strips the types and builds the files the browser loads.

querySelector returns Element | null

Here is the first thing every TypeScript developer meets in the browser:

TypeScript
const button = document.querySelector('#save');
button.addEventListener('click', save);
// error TS18047: 'button' is possibly 'null'.

querySelector returns null when nothing matches, and the type says so. You have three ways to deal with it:

TypeScript
// 1. Check, and handle the missing case (best for optional elements)
const banner = document.querySelector('.banner');
if (banner) {
  banner.remove();
}

// 2. Optional chaining when doing nothing is fine
document.querySelector('.banner')?.remove();

// 3. Throw early when the element MUST exist (best for app shells)
const app = document.querySelector('#app');
if (!app) {
  throw new Error('#app not found');
}

You'll also see document.querySelector('#app')! with the non-null assertion. It compiles, but if the markup changes it fails later with a vague "Cannot read properties of null" error instead of a clear message.

Tag selectors return specific types

The return type also depends on the selector. With a plain tag name, TypeScript returns the matching element interface; with anything else, it can only promise Element:

TypeScript
const input = document.querySelector('input');        // HTMLInputElement | null
const svg = document.querySelector('svg');            // SVGSVGElement | null
const email = document.querySelector('#email');       // Element | null
const byId = document.getElementById('email');        // HTMLElement | null
const items = document.querySelectorAll('li');        // NodeListOf<HTMLLIElement>

How does a string decide the type? lib.dom.d.ts contains a map from tag names to interfaces, HTMLElementTagNameMap, and querySelector has a generic overload whose type parameter is constrained to that map's keys. You can build the same thing yourself, which is the best way to understand it:

TypeScript How querySelector picks a type from a tag name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
[email protected]
submit
INPUT
no image on this page

The trick is the indexed access type TagNameMap[K] (see keyof and indexed access types). When you pass 'input', K is inferred as the literal "input", so the return type is TagNameMap['input'], which is HTMLInputElement. A string like '#email' isn't a key of the map, so the second overload applies. (The as HTMLInputElement casts inside the fake page are only there to build test data.)

Narrowing to the element you need

querySelector('#email') gives you an Element, which has no value. To read the input's value you must convince TypeScript that it's an HTMLInputElement. There are two ways, and only one is safe:

TypeScript
// Unsafe: an assertion. If #email is actually a <div>, value is undefined.
const email1 = document.querySelector('#email') as HTMLInputElement;

// Safe: a runtime check that also narrows the type
const email2 = document.querySelector('#email');
if (email2 instanceof HTMLInputElement) {
  console.log(email2.value); // email2 is HTMLInputElement here
}

DOM interfaces such as HTMLInputElement are real classes in the browser, so instanceof works at runtime and TypeScript narrows on it. You can also use the generic form document.querySelector<HTMLInputElement>('#email'), but that's just an assertion in disguise: nothing checks it.

Most projects end up with a small helper that combines the lookup and the check. Here it is with hand-written classes standing in for the DOM ones:

TypeScript A safe getElement helper with instanceof

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
[email protected], save disabled=false
#save is missing or is not a HTMLInputElement

The parameter type new (...args: never[]) => T is a constructor type: it accepts any class whose instances are T, and TypeScript infers T from the class you pass. The never[] parameter list means "whatever arguments the constructor takes": we never call it, we only use it with instanceof, so any constructor fits. In a real project the same helper works unchanged with the browser's HTMLInputElement, HTMLSelectElement and so on.

Typing events

addEventListener is typed by event name. In the DOM types, each element has an event map such as HTMLElementEventMap, which says 'click' produces a MouseEvent, 'keydown' a KeyboardEvent, 'input' an InputEvent and 'change' a plain Event:

TypeScript
const field = document.querySelector('input');

field?.addEventListener('keydown', (event) => {
  // event: KeyboardEvent, inferred from the event name
  if (event.key === 'Enter') {
    event.preventDefault();
  }
});

field?.addEventListener('input', (event) => {
  // event.target is EventTarget | null, NOT HTMLInputElement
  const target = event.currentTarget as HTMLInputElement;
  console.log(target.value);
});

Two details trip people up:

  • event.target is EventTarget | null. The target can be any descendant (a click on a <span> inside a button targets the span), so TypeScript can't promise more. Narrow it with instanceof, or use event.currentTarget, which is the element the listener was attached to.
  • Custom event names aren't typed. addEventListener('my-event', ...) falls back to the plain Event type unless you extend the event map.

The pattern behind typed listeners is a map from names to event types, again with K extends keyof Map. Here's a self-contained version:

TypeScript A typed event target like the DOM's

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
key Shift+a
click at 40,12

Each listener's parameter type is looked up from the event name, so you never annotate event yourself. The listener storage uses a mapped type to keep one array per event name. The type-safe event emitter project builds a complete version of this idea.

Now see what the types prevent. A click listener can't read key, because mouse events don't have one:

TypeScript Using the wrong event property (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This doesn't compile, and both errors are exactly the ones you'd get with the real DOM types:

TEXT
main.ts(17,21): error TS2339: Property 'key' does not exist on type 'MouseEvent'.
main.ts(19,4): error TS2345: Argument of type '"scroll"' is not assignable to parameter of type 'keyof ElementEventMap'.

Forms

Form controls are where narrowing matters most, because every control has different properties:

TypeScript
const form = document.querySelector('form');

form?.addEventListener('submit', (event) => {
  event.preventDefault();
  const data = new FormData(form);

  // FormData.get returns FormDataEntryValue | null (string | File | null)
  const name = data.get('name');
  if (typeof name !== 'string' || name.trim() === '') {
    return;
  }

  const age = form.querySelector('input[name="age"]');
  if (age instanceof HTMLInputElement) {
    console.log(name, age.valueAsNumber); // number, NaN when empty
  }
});

Notice that form is still narrowed inside the listener, because form is a const. With let, older TypeScript versions forgot the narrowing in callbacks; since 5.4 it survives when the variable isn't reassigned afterwards (see what's new).

Typing fetch responses

fetch is fully typed, but the most important method is deliberately loose: response.json() can't know what the server sends. In lib.dom.d.ts it returns Promise<any>; in Node's types it returns Promise<unknown>. Either way, you must decide what the data is, and the safe way is to treat it as unknown and check it.

Our editor runs on Node, which has fetch built in. There's no network, but fetch can read a data: URL, which is perfect for a demo:

TypeScript fetch with a typed, validated result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
#7 ADA
Response is not a User

Writing const user: User = await response.json() would also compile in the browser (because of any), but it's an unchecked promise to yourself. If the API changes, the error shows up far away, in code that trusted the data. The Typing APIs and JSON data lesson goes much further: generic fetch wrappers, schema libraries like Zod and generated types.

Extending the DOM types

Sometimes you need to add to the built-in types, for example a custom element or a value your app stores on window. Because lib.dom.d.ts uses interfaces, you can merge new members into them with declare global (see declaration files):

TypeScript
// star-rating.ts (a module, thanks to the export)
export {};

declare global {
  interface Window {
    appVersion: string;
  }
  interface HTMLElementTagNameMap {
    'star-rating': StarRating;
  }
}

class StarRating extends HTMLElement {
  value = 0;
}
customElements.define('star-rating', StarRating);

// Now this is typed as StarRating | null:
const rating = document.querySelector('star-rating');

Adding the tag to HTMLElementTagNameMap is exactly what made querySelector('input') work in the first TryIt: the generic overload looks the tag up in that map.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of document.querySelector(".card")?

    A class selector could match any kind of element, and it might match nothing. Only plain tag names like 'div' give a more specific type.
  2. 2. Which line safely gives you an HTMLInputElement you can read .value from?

    The instanceof check runs in the browser and narrows the type. The first two are unchecked assertions, and the last one does not compile.
  3. 3. In a click listener, what is the type of event.target?

    The target can be any descendant, or not an element at all, so it is typed as EventTarget | null. currentTarget refers to the element the listener is attached to.
  4. 4. In the browser types, what does response.json() return?

    lib.dom types json() as Promise<any>. Assigning it to unknown and checking it with a type guard keeps the rest of your code honest.
  5. 5. Our editor's TypeScript has no DOM types. Why?

    The DOM types are in lib.dom.d.ts, which is only included when lib contains "dom" (or when lib is left at its defaults). The editor runs on Node.

Summary

  • Add "dom" and "dom.iterable" to lib for browser code; they declare document, every element interface, events and Web APIs like fetch.
  • querySelector returns Element | null, or a specific type such as HTMLInputElement | null for plain tag names, thanks to HTMLElementTagNameMap.
  • Handle null with a check, optional chaining or an early throw; narrow to a specific element with instanceof rather than as.
  • Listener parameters are inferred from the event name ('keydown' gives KeyboardEvent); event.target is only EventTarget | null.
  • response.json() is untyped: assign it to unknown and validate it before use.
  • Extend the built-in types with declare global and interface merging, for example to register custom elements.

Next: Typing APIs and JSON Data