- Courses
- đź’»Programming Languages
- 🛡️TypeScript
- Common TypeScript Usage Patterns
- Working with DOM & Browser APIs
On this page
Working with DOM & Browser APIs in TypeScript
Updated on July 27, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
In plain JavaScript, the DOM is a minefield: document.querySelector() can return anything, casting it to whatever type seems convenient works without complaint, and calling a method that doesn't exist on the actual element only fails once the code runs in a browser. TypeScript closes this gap by tracking exactly what kind of element a query can return, exactly what kind of object an event handler receives, and by refusing to compile code that accesses a property the compiler cannot prove exists. The practical effect is that entire categories of DOM bugs — null references, wrong element types, mistyped event properties — get caught while writing the code instead of while a user is clicking around a broken page.
Understanding this well requires looking at three things working together: how TypeScript types elements returned from the DOM, how it infers the exact shape of an event object from the event name alone, and how to narrow a generic EventTarget down to something usable when the automatic inference isn't enough.
Built-in DOM Types​
TypeScript's standard library ships with a full model of the browser environment. Every element interface (HTMLElement, HTMLInputElement, HTMLButtonElement, and dozens more), every event interface (Event, MouseEvent, KeyboardEvent, and so on), and the relationships between them are already defined. This matters because the DOM is not a flat structure: an HTMLInputElement is a more specific kind of HTMLElement, which is a more specific kind of Element, and TypeScript understands that hierarchy. That's what allows it to know that input.value is valid but div.value is not, without a single manual type declaration on the developer's part.
Querying elements​
Consider a basic query:
const button = document.querySelector("button");
Hovering over button in an editor shows:
const button: HTMLButtonElement | null
Two things are happening here, and both are worth understanding rather than memorizing. First, TypeScript looked at the CSS selector string "button" itself and matched it against a built-in mapping of tag names to element interfaces, which is how it knew to return HTMLButtonElement specifically instead of a generic Element. Second, it added | null to the type automatically, because a selector might not match anything in the document, and querySelector reflects that possibility honestly rather than pretending the element is guaranteed to exist. Any code that tries to call button.disabled without first checking for null will fail to compile, which forces a decision about what should happen when the element isn't found — a decision that plain JavaScript lets a developer skip until it causes a crash in production.
Querying by ID and type assertions​
getElementById works differently. It cannot infer a specific element type from the ID string the way querySelector can from a tag selector, because IDs carry no information about what kind of element they belong to:
const input = document.getElementById("username");
This resolves to HTMLElement | null — accurate, but not specific enough to access input-only properties like .value. There are two ways to get a more precise type. The first is a type assertion:
const input = document.getElementById("username") as HTMLInputElement;
This tells the compiler "trust me, this is an input element," without any actual verification. It compiles cleanly even if the element with that ID is really a <div>, and the mistake would only surface as a runtime error. The safer option is passing the desired type as a generic argument to querySelector instead:
const input = document.querySelector<HTMLInputElement>("#username");
This still doesn't verify the element's type at runtime — that isn't something TypeScript can check for a query result — but it keeps the intent explicit and colocated with the query itself, and it avoids layering a separate assertion on top of an already-imprecise return type. Neither approach replaces an actual runtime check when correctness truly matters, which is where narrowing (covered further down) becomes necessary.
Event Typing​
Handling events in raw JavaScript means the event object passed to a listener is effectively a black box — the correct properties have to be known from memory or documentation, and nothing warns against typos or wrong assumptions. TypeScript removes that guesswork by tying the name of an event directly to the type of the object the listener will receive.
How the inference works​
const button = document.querySelector("button");
button?.addEventListener("click", (event) => {
// event: MouseEvent
console.log(event.clientX);
});
The string "click" is doing more work than it looks like. TypeScript's DOM library defines a lookup table (internally called HTMLElementEventMap) that pairs every standard event name with its corresponding event interface: "click" maps to MouseEvent, "keydown" maps to KeyboardEvent, "input" maps to InputEvent, and so on for the full set of DOM events. When addEventListener is called, TypeScript reads the literal string passed as the first argument, looks it up in that table, and types the event parameter of the callback accordingly — automatically, with no annotation required. This is why event.clientX is valid in the example above: MouseEvent genuinely has a clientX property, and the compiler already knows that before the code runs.
Keyboard events​
document.addEventListener("keydown", (event) => {
console.log(event.key); // event: KeyboardEvent
});
Because the event name here is "keydown" rather than "click", the same lookup mechanism resolves event to KeyboardEvent instead of MouseEvent. Trying to read event.clientX inside this callback would fail to compile, since KeyboardEvent doesn't have that property — a mistake that's easy to make when copying and adapting code, and one TypeScript catches immediately.
Input events​
const input = document.querySelector("input");
input?.addEventListener("input", (event) => {
console.log(event.data); // event: InputEvent
});
The same pattern applies again: "input" resolves to InputEvent, which exposes a data property representing the text that was just typed. The practical benefit compounds across a codebase — every event handler gets accurate autocomplete, and any property access that doesn't belong to that specific event type is flagged before deployment rather than discovered by a user.
Narrowing Event Targets​
Event typing handles the event object itself, but it does not automatically know what the event's target — the specific element that triggered it — actually is. This is one of the most common sources of DOM bugs in JavaScript, because it's tempting to assume the target is always the expected element type without verifying it.
Why target is risky​
document.addEventListener("input", (e) => {
console.log(e.target.value); // ❌ Might not exist
});
event.target is typed as EventTarget, a very general interface that doesn't guarantee a .value property. This is a deliberate and accurate limitation: an "input" event listener attached to document could theoretically fire because of any input element anywhere in the page, and TypeScript has no way to know in advance which one. Attempting to compile the code above produces an error along these lines:
Property 'value' does not exist on type 'EventTarget'
Rather than being an inconvenience, this error is the compiler doing exactly what it should: refusing to let code assume something it cannot verify.
Safe narrowing with instanceof​
The most direct fix is a runtime check using instanceof, which both verifies the element type when the code actually executes and narrows the compile-time type for everything inside the if block:
document.addEventListener("input", (event) => {
const target = event.target;
if (target instanceof HTMLInputElement) {
console.log(target.value); // âś” Safe
}
});
Once TypeScript sees the instanceof check succeed, it treats target as HTMLInputElement for the remainder of that block, so .value becomes valid. This is narrowing in the fullest sense: the same variable has a broader type outside the check and a more specific one inside it, and the compiler tracks that transition automatically.
Type predicates for reusable checks​
When the same narrowing logic needs to run in multiple places, wrapping it in a dedicated function keeps the code from repeating itself. A type predicate is a function whose return type tells the compiler exactly what a true result means for the input's type:
function isInput(el: EventTarget | null): el is HTMLInputElement {
return el instanceof HTMLInputElement;
}
document.addEventListener("input", (event) => {
if (isInput(event.target)) {
console.log(event.target.value);
}
});
The el is HTMLInputElement return annotation is what makes this work as a narrowing tool rather than a plain boolean function. Anywhere isInput(...) is used inside an if condition, TypeScript narrows the checked value the same way it would for an inline instanceof, but the logic itself only needs to be written once.
currentTarget as a safer alternative​
When a listener is attached directly to a specific element rather than to a shared ancestor, event.currentTarget is usually a better choice than event.target, because its type is already known from the element the listener was attached to:
button.addEventListener("click", (event) => {
const btn = event.currentTarget; // HTMLButtonElement
console.log(btn.disabled);
});
target identifies whatever element the event originated from, which could be a child of button. currentTarget identifies the element the listener itself is bound to — button, in this case — which is exactly why TypeScript can type it precisely without any narrowing step being necessary.
Bringing It Together​
A realistic form handler shows all three pieces working in combination:
const form = document.querySelector("form");
const input = document.querySelector<HTMLInputElement>("#email");
form?.addEventListener("submit", (event) => {
event.preventDefault();
if (!input) return;
const value = input.value.trim();
if (value.includes("@")) {
console.log("Valid email:", value);
} else {
console.log("Invalid email");
}
});
Every step in this snippet reflects a decision TypeScript is enforcing rather than merely suggesting. form and input are both typed as possibly null, so the code has to handle that case — the ?. and the early return — before proceeding. The submit event is automatically typed as SubmitEvent through the same event-map mechanism covered earlier, which is why event.preventDefault() is available without any manual typing. And because input was queried with the HTMLInputElement generic, input.value is known to be a string the moment it's read, with no assertion or runtime check required at that point — the safety was already established earlier, when the element was queried.
Key Takeaways​
The type safety TypeScript brings to DOM code comes from three mechanisms working together, and each one closes a different gap that plain JavaScript leaves open. Built-in DOM types make element queries return specific, accurate types instead of a generic and unhelpful Element. The event-map system reads the literal event name passed to addEventListener and infers the exact event interface from it, so properties like clientX or key are available — and correctly restricted — without manual annotation. Narrowing, whether through instanceof, a reusable type predicate, or currentTarget, handles the one thing automatic inference cannot: knowing what element actually triggered an event. Together, these turn DOM programming from a runtime guessing game into something the compiler actively verifies before the code ever reaches a browser.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Typing Common JS Patterns
Next
Working with Node.js
-
Built-in DOM Types
- Querying elements
- Querying by ID and type assertions
-
Event Typing
- How the inference works
- Keyboard events
- Input events
-
Narrowing Event Targets
- Why target is risky
- Safe narrowing with instanceof
- Type predicates for reusable checks
- currentTarget as a safer alternative
-
Bringing It Together
-
Key Takeaways
