← Back to TypeScript Course | Chapter 12: TypeScript with DOM | Lesson 1 of 6

DOM Type Definitions

TypeScript includes built-in DOM type definitions for browser objects such as Document, HTMLElement, and HTMLInputElement. These types provide type checking and editor support when working with HTML.

Document Type

The Document type describes the single document object every page has access to, including its methods for querying and creating elements, and comes built into TypeScript's DOM library without any extra install.

Example: Document Type

typescript
const heading: HTMLElement = document.createElement("h1");
heading.textContent = "Hello";
console.log(heading.tagName);

HTMLElement Type

HTMLElement is the general base type for any element in the DOM tree, exposing shared properties like style, className, and addEventListener that every kind of element has in common.

Example: HTMLElement Type

typescript
const el: HTMLElement = document.createElement("div");
el.className = "box";
el.style.color = "blue";
console.log(el.className, el.style.color);

Specific Element Types

More specific element types like HTMLInputElement or HTMLButtonElement extend HTMLElement with properties unique to that tag, such as .value on inputs, so casting to the right specific type unlocks the right specific properties.

Example: Specific Element Types

typescript
const input: HTMLInputElement = document.createElement("input");
input.value = "hello";
console.log(input.value);

DOM Collections

DOM collection types like NodeList and HTMLCollection represent groups of elements returned by methods like querySelectorAll, and they differ slightly in whether they're live-updating and which array methods they support directly.

Example: DOM Collections

typescript
const container = document.createElement("div");
container.innerHTML = "<p>One</p><p>Two</p>";
const paragraphs: NodeListOf<HTMLParagraphElement> = container.querySelectorAll("p");
console.log(paragraphs.length);

Why DOM Types Matter

Using the correct DOM types instead of any means the compiler catches mistakes like reading .value on an element that isn't actually an input, well before that bug would otherwise surface as a runtime crash in the browser.

Example: Why DOM Types Matter

typescript
const input: HTMLInputElement = document.createElement("input");
input.value = "42";
// input.value is known to be a string, caught at compile time
console.log(input.value.length);
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.