Typing the DOM
Interacting with browser APIs safely.
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.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
Event.targetis generic. You must cast it usingas HTMLInputElement.querySelectorreturnsElement | null. You must check fornull.- 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.