skip to content
Keshav Mohta

DOM typing

/ 1 min read

DOM typings

Check code on playground

we will explore and set type for DOM method; such as document.querySelector() and document.querySelectorAll()

❌ below is not working

const radioInputList = document.querySelectorAll<RadioNodeList>("input[type=radio]");
radioInputList.forEach((r) => (r.checked = r.defaultValue === "X"));

✅ but this works

const radioInputList = document.querySelectorAll<HTMLInputElement>("input[type=radio]");
radioInputList.forEach((r) => (r.checked = r.defaultValue === "X"));

❌ but this will not work; adding typing ahead to variable

const radioInput: HTMLInputElement = document.querySelectorAll("input[type=radio]");

✅ this works ( with as)

const radioInputList = document.querySelectorAll("input[type=radio]") as NodeListOf<HTMLInputElement>;
radioInputList.forEach((r) => (r.checked = r.defaultValue === "X"));

❌ but this will not work ( type )

const radioInputList = document.querySelectorAll < NodeListOf<HTMLInputElement>("input[type=radio]");
radioInputList.forEach((r) => (r.checked = r.defaultValue === "X"));

❌ neither this works (assign)

const radioInputList: NodeListOf<HTMLInputElement> = document.querySelectorAll("input[type=radio]");

❎ below syntax are not working

const radioInputList: HTMLInputElement = document.querySelectorAll("input[type=radio]");
const radioInputList: Element = document.querySelectorAll("input[type=radio]");
const radioInputList: HTMLInputElement[] = document.querySelectorAll("input[type=radio]");
const radioInputList: Element[] = document.querySelectorAll("input[type=radio]");

✅ and here is separate type for both DOM method as per my approach

const video = document.querySelector<HTMLVideoElement>("video"); // HTMLVideoElement | null
const audios = document.querySelectorAll("audio") as NodeListOf<HTMLAudioElement>;

Hope it helps.