# Typing the DOM

> Interacting with browser APIs safely.

Subject: TypeScript | Lesson 50 of 54 | 4 min read
Interactive lesson: https://codewithanimation.in/typescript/typing-the-dom
Previous: [Declaration Files (.d.ts)](https://codewithanimation.in/typescript/declaration-files-dts.md) | Next: [React Component Typing](https://codewithanimation.in/typescript/react-component-typing.md)

## 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);
});
```

## Common mistake: Null Elements

When you use `document.querySelector(".my-class")`, TypeScript types the result as `Element | null`.

You must always check if the element actually exists before trying to access its properties, or you will get a runtime crash.

## Tip: React vs Vanilla

If you are using React, you rarely need manual assertions. Instead, you provide a generic to the event type: `e: React.ChangeEvent<HTMLInputElement>`.

## Try it: Try it

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

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/typescript/typing-the-dom

## Check yourself

### Question 1

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

- A. Because the ID might not exist in the HTML document.
- B. Because TypeScript doesn't support the DOM API.
- C. Because 'my-input' is a string, which can be null.

Correct answer: A

DOM queries are dynamic. Since the element might not actually be on the page when the script runs, the return type is a Union including `null`. You must handle the `null` case to satisfy strict mode.

## 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`).
