Episode 11 of 21

The DOM & Type Casting

Interacting with the DOM in TypeScript — element types, type casting, and event handling.

The DOM & Type Casting

TypeScript has built-in types for DOM elements, but sometimes you need to help it understand what specific element you're working with.

Selecting DOM Elements

const anchor = document.querySelector("a");
// Type: HTMLAnchorElement | null

if (anchor) {
    console.log(anchor.href);  // ✅ TypeScript knows 'href' exists
}

The Null Problem

DOM queries can return null. TypeScript requires you to handle this:

const form = document.querySelector("form");
// form is HTMLFormElement | null

console.log(form.children);  // ❌ Error — form might be null

// Solution 1: if check
if (form) {
    console.log(form.children);
}

// Solution 2: non-null assertion (!)
const form2 = document.querySelector("form")!;
console.log(form2.children);  // ✅

Type Casting

When selecting by class/id, TypeScript only knows it's a generic Element. Use type casting:

const form = document.querySelector(".my-form") as HTMLFormElement;
// Now TypeScript knows it's a form

const input = document.querySelector("#amount") as HTMLInputElement;
console.log(input.value);  // ✅ 'value' is available

Common DOM Types

ElementType
<a>HTMLAnchorElement
<form>HTMLFormElement
<input>HTMLInputElement
<select>HTMLSelectElement
<div>HTMLDivElement
<p>HTMLParagraphElement

Event Handling

const form = document.querySelector("form")!;
form.addEventListener("submit", (e: Event) => {
    e.preventDefault();
    console.log("submitted");
});

Key Takeaways

  • DOM methods return Element | null — handle null cases
  • Use ! for non-null assertion when you're sure the element exists
  • Use as HTMLType for type casting with class/id selectors
  • TypeScript has types for all HTML elements