Typing the DOM

Interacting with browser APIs safely.

TypeScript4 min readConcept 50 of 54

The DOM Types

When you use TypeScript in a browser environment, it comes with a built-in library of DOM types (like HTMLElement, HTMLInputElement, and Event).

Because the DOM is highly dynamic, TypeScript often returns generic, wide types that you must narrow down.

The Event.target Problem

A classic beginner trap is typing e.target.value inside an event listener. TypeScript will throw an error: Property 'value' does not exist on type 'EventTarget'.

Why? Because an event can be triggered by *anything* (a <div>, a <body>, a <p>). Only specific elements like <input> actually have a .value property.

Syntax

typescript document.addEventListener("change", (e: Event) => { // ❌ Error: EventTarget doesn't have .value console.log(e.target.value); // ✅ Type Assertion (Casting) const input = e.target as HTMLInputElement; console.log(input.value); });

Try it

Toggle the type assertion on the EventTarget and watch how the compiler responds to accessing the .value property.

// Listen to an input event in the DOM
document.addEventListener("input", (e: Event) => {
const target = e.target as HTMLInputElement;
console.log(target.value);
Property 'value' does not exist on type 'EventTarget'.
});
TypeScript Compiler
Type Error
An event can be fired by ANY element in the DOM (like a div or body). A generic EventTarget does not have a .value property.
Data Flow
...Blocked by TS

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Why does `document.getElementById('my-input')` return `HTMLElement | null`?

Remember this

  • Event.target is generic. You must cast it using as HTMLInputElement.
  • querySelector returns Element | null. You must check for null.
  • The TypeScript compiler ships with a comprehensive library of DOM types (e.g., lib.dom.d.ts).

Done with this concept?

Mark it complete to track your progress. No login needed.