DOM Typing
Query with a concrete type
querySelector returns Element | null. Narrow null, then assert or check a more specific element type.
const el = document.querySelector("#title");
if (el) {
el.textContent = "Hello";
}
Use HTML element types
Cast or use generics when you need input-specific properties like value.
const input = document.querySelector<HTMLInputElement>("#email");
if (input) {
console.log(input.value);
}
Listen for events
Event handlers receive typed events. Form submits use SubmitEvent in modern lib settings.
const form = document.querySelector("form");
form?.addEventListener("submit", (event) => {
event.preventDefault();
});
DOM checklist
- Always handle
nullfrom query helpers - Include DOM libs in tsconfig (
"dom"inlib) - Prefer
textContentoverinnerHTMLfor plain text - Keep TypeScript on the authoring side; the browser still runs JavaScript
Comments
One comment per signed-in account. Comments are saved with this page’s URL.