Frontend development · Intermediate · 25 min
Type-check browser DOM code with TypeScript
By Padding · Updated 18 Nov 2026
Node.js 26 · TypeScript 7.0.2 · Vite 8.3.8 · create-vite 9.3.4 · checked in the node:26 image
You will turn a small untyped DOM script into TypeScript 7 in a Vite project, fix every error the compiler reports without casts or stray non-null assertions, check fetched JSON at runtime, and run tsc --noEmit in CI and a Playwright test in Chromium.
On this page
A plain JavaScript file that works in the browser can hide several bugs at once: an element that is not on the page, a property that exists on inputs but not on the element you actually found, and JSON from a server that is not shaped the way the code assumes. TypeScript reports all three before the code runs, but only if you answer its questions honestly. Answer them with casts and !, and the warnings go quiet while the bugs stay.
In this tutorial you take a small, working-looking script for a prepaid data bundle planner and convert it to TypeScript in a Vite project. The planner asks how many megabytes someone uses a day and for how long, loads a price list from bundles.json, and suggests the cheapest bundle that covers it. Prepaid data is how most people in Nigeria, Kenya, Ghana and much of the world pay for mobile internet, so a page like this often runs on a low-end Android phone over a weak connection. That is exactly where a half-loaded price list or a missing element turns into a blank screen.
You fix each kind of error the compiler raises, keep the checks that matter at runtime, then make the type check run on every push and prove the finished page works in a real browser. For what each line of a tsconfig.json does in general, see set up a TypeScript 7 project. This tutorial only covers the settings that matter for browser code.
Step 1 · Scaffold a Vite TypeScript project
Create the project from Vite's vanilla-ts template, pinning create-vite so you get the same files as this tutorial, and install its dependencies:
cd ~
npm create vite@9.3.4 ts-dom-demo -- --template vanilla-ts --no-interactive
cd ts-dom-demo
npm install
npx tsc --version
npm ls viteThe template is a counter demo. Delete its demo files so the project holds only your code:
rm -r src/assets src/counter.ts src/style.css public/icons.svg
ls src publicpublic/favicon.svg stays, because index.html links to it.
Check it worked
npx tsc --version prints Version 7.0. followed by a patch number, and npm ls vite ends in vite@8.3. and a patch number. The final ls shows only main.ts in src and only favicon.svg in public.
Step 2 · Bring in the JavaScript and run the compiler
Write the page. It has a form with a number input, a select, two buttons and an <output> element for the answer. The submit button starts disabled, because there is nothing to search until the price list has loaded:
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Data bundle planner</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 26rem; margin: 0 auto; padding: 1rem; line-height: 1.5; }
form { display: grid; gap: 0.5rem; }
input, select, button { font: inherit; min-height: 2.75rem; }
output { display: block; margin-top: 1rem; font-weight: 600; }
</style>
</head>
<body>
<main>
<h1>Data bundle planner</h1>
<form id="planner">
<label for="daily-mb">Data you use a day (MB)</label>
<input id="daily-mb" type="number" min="1" step="1" value="150" required />
<label for="days">How long you need it for</label>
<select id="days">
<option value="1">1 day</option>
<option value="7" selected>7 days</option>
<option value="30">30 days</option>
</select>
<button id="check" type="submit" disabled>Find a bundle</button>
<button class="reset" type="button">Start again</button>
</form>
<output id="result" for="daily-mb days"></output>
</main>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
HTMLAdd the price list. Files in public/ are served as they are, so the page can fetch it at /bundles.json. The prices are in airtime credit for a made-up network:
cat > public/bundles.json <<'JSON'
[
{ "name": "Daily 100 MB", "mb": 100, "days": 1, "price": 100 },
{ "name": "Weekly 750 MB", "mb": 750, "days": 7, "price": 500 },
{ "name": "Weekly 1.5 GB", "mb": 1536, "days": 7, "price": 1000 },
{ "name": "Monthly 3 GB", "mb": 3072, "days": 30, "price": 1500 },
{ "name": "Monthly 10 GB", "mb": 10240, "days": 30, "price": 3500 }
]
JSONNow the script, exactly as it might have been written in a .js file. In your own project this is the moment you rename main.js to main.ts: nothing in the code changes, only what the compiler is willing to assume about it.
cat > src/main.ts <<'TS'
const form = document.querySelector('#planner')
const dailyInput = document.querySelector('#daily-mb')
const daysSelect = document.querySelector('#days')
const checkButton = document.querySelector('#check')
const resetButton = document.querySelector('.reset')
const result = document.querySelector('#result')
let bundles = []
async function loadBundles() {
const response = await fetch('/bundles.json')
bundles = await response.json()
checkButton.disabled = false
}
function cheapestFor(neededMb, days) {
return bundles
.filter((bundle) => bundle.mb >= neededMb && bundle.days >= days)
.sort((a, b) => a.price - b.price)[0]
}
form.addEventListener('submit', (event) => {
event.preventDefault()
const days = Number(daysSelect.value)
const needed = dailyInput.valueAsNumber * days
const best = cheapestFor(needed, days)
result.textContent = best
? `${best.name} covers ${needed} MB over ${days} days for ${best.price} credit.`
: `No single bundle covers ${needed} MB. Try a shorter period.`
})
function handleReset() {
form.reset()
result.textContent = ''
}
resetButton.addEventListener('click', handleReset)
loadBundles()
TS
npx tsc --noEmit || echo "tsc exited with status $?"--noEmit checks the types and writes no JavaScript. Vite does its own compiling, so in a Vite project tsc is only ever a checker.
Check it worked
tsc lists 16 errors and exits with a non-zero status. They fall into four groups, and the rest of the tutorial deals with each:
TS18047: 'form' is possibly 'null'.querySelectorreturnsnullwhen nothing matches, and the compiler cannot see your HTML.TS2339: Property 'value' does not exist on type 'Element'.Matching by id or class gives a plainElement, which has novalue,disabledorreset.TS7006: Parameter 'neededMb' implicitly has an 'any' type.The function's inputs are unknown.TS7034: Variable 'bundles' implicitly has type 'any[]' ...The empty array and the fetched JSON give the compiler nothing to go on.
Step 3 · See where the DOM types come from
document, HTMLInputElement and fetch are not part of JavaScript the language. They are browser APIs, and TypeScript only knows them because of the lib setting. Look at the template's config:
cat tsconfig.jsonThree lines matter for browser code:
"lib": ["ES2023", "DOM"]loads the type definitions for the language features of ES2023 and for the browser's DOM. Since TypeScript 6.0,DOMalso includes what used to be split out asDOM.Iterable, such as looping over aNodeListwithfor...of, so you no longer list both."types": ["vite/client"]adds Vite's own globals, such asimport.meta.envand the types for importing images and CSS. It does not add the DOM."noEmit": truemakes plaintsca checker, the same as passing--noEmit.
There is no "strict": true in the file. You do not need it: since TypeScript 6.0, strict mode is on unless you turn it off, which is why the null and any errors appeared.
See what the compiler says without the DOM by overriding lib for one run:
npx tsc --noEmit --lib es2023 > no-dom.txt || echo "tsc exited with status $?"
grep -c "Cannot find name 'document'" no-dom.txt
rm no-dom.txtA Node.js project has the opposite setup: no DOM in lib, and @types/node in types. If a shared folder is checked by both configs, browser-only code will fail the Node check, and that is the compiler telling you the truth.
Check it worked
grep -c prints 6, one line for each document.querySelector call. Each of those errors reads TS2584: Cannot find name 'document'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'. Your tsconfig.json is unchanged, because the --lib flag only applied to that one run.
Step 4 · Narrow elements before you use them
document.querySelector('#daily-mb') has the type Element | null. To use .valueAsNumber you need TypeScript to agree that the value is an HTMLInputElement. The honest way is to check it at runtime with instanceof. Inside the if, TypeScript narrows the type for you:
const dailyInput = document.querySelector('#daily-mb')
if (!(dailyInput instanceof HTMLInputElement)) {
throw new Error('#daily-mb is missing or is not an <input>')
}
dailyInput.valueAsNumber // HTMLInputElement here, never nullinstanceof rules out null and the wrong element type in one check, and it stays in the shipped code. If someone renames the id or turns the input into a <textarea>, the page fails at load with a message that names the problem, instead of a vague Cannot read properties of null later.
Writing that if six times is noise, so put it in a function. The second argument is the element class, used both for the runtime instanceof check and as the return type:
cat > src/elements.ts <<'TS'
// A DOM class such as HTMLInputElement, used both as a value (for instanceof)
// and as the type of the element it describes.
type ElementClass<T extends Element> = { new (): T; prototype: T }
export function requireElement<T extends Element>(selector: string, type: ElementClass<T>): T {
const element = document.querySelector(selector)
if (!(element instanceof type)) {
throw new Error(`Expected ${selector} to be a ${type.name}, found ${element ? element.tagName : 'nothing'}`)
}
return element
}
export const form = requireElement('#planner', HTMLFormElement)
export const dailyInput = requireElement('#daily-mb', HTMLInputElement)
export const daysSelect = requireElement('#days', HTMLSelectElement)
export const checkButton = requireElement('#check', HTMLButtonElement)
export const resetButton = requireElement('.reset', HTMLButtonElement)
export const result = requireElement('#result', HTMLOutputElement)
TS
npx tsc --noEmit || echo "tsc exited with status $?"You will meet two shorter forms in other people's code. Know what each one does and does not promise:
// Matched by tag name: TypeScript picks the element type for you.
const planner = document.querySelector('form') // HTMLFormElement | null
// A type argument is a claim, not a check.
const reset = document.querySelector<HTMLButtonElement>('.reset') // HTMLButtonElement | null
// The ! removes null from the type, but not from the page.
const missing = document.querySelector<HTMLButtonElement>('#no-such-id')!
missing.disabled = true // compiles, then throws in the browser- A tag-name selector such as
'form'or'input'is genuinely typed: the DOM lib maps each tag name to its class, and you still handlenull. querySelector<HTMLButtonElement>('.reset')is the generic form. TypeScript believes you without checking, so if the markup changes to<a class="reset">, the compiler stays quiet. It is acceptable when the element comes from markup in the same component and you still handlenull.- The non-null
!tells the compiler a value is nevernullorundefined, and it does nothing at runtime. Keep it as a last resort for cases the compiler genuinely cannot follow, such as an element your own code created two lines earlier. For anything that comes from the HTML, theinstanceofcheck costs one line and catches real mistakes.
Check it worked
tsc still reports errors, but every one of them is in src/main.ts; none mention src/elements.ts. Hover over dailyInput in elements.ts in an editor with TypeScript support, such as VS Code: the tooltip shows const dailyInput: HTMLInputElement, with no | null.
Step 5 · Check fetched JSON at runtime
response.json() is typed as Promise<any> in the DOM lib. any switches type checking off for everything it touches, so bundles = await response.json() lets any shape at all flow into the rest of the program. Writing as Bundle[] does not help: a cast is a claim, the same as the generic querySelector, and a server that sends "mb": "750" as a string still gets through.
Instead, give the JSON the type unknown, which forces a check before use, and write a type guard: a function that checks the value at runtime and returns value is Bundle[], so TypeScript narrows the type when it returns true:
cat > src/bundles.ts <<'TS'
export interface Bundle {
name: string
mb: number
days: number
price: number
}
function isBundle(value: unknown): value is Bundle {
return (
typeof value === 'object' &&
value !== null &&
'name' in value && typeof value.name === 'string' &&
'mb' in value && typeof value.mb === 'number' && value.mb > 0 &&
'days' in value && typeof value.days === 'number' && value.days > 0 &&
'price' in value && typeof value.price === 'number' && value.price >= 0
)
}
function isBundleList(value: unknown): value is Bundle[] {
return Array.isArray(value) && value.every(isBundle)
}
export async function loadBundles(url: string): Promise<Bundle[]> {
const response = await fetch(url)
if (!response.ok) {
throw new Error(`${url} answered ${response.status}`)
}
const data: unknown = await response.json()
if (!isBundleList(data)) {
throw new Error(`Not a list of bundles: ${url}`)
}
return data
}
TSEach 'name' in value check lets TypeScript treat value.name as a property it may read, and the typeof after it settles its type, so the guard needs no casts. Because data is unknown, deleting the isBundleList check makes return data a compile error: the compiler will not let unchecked JSON out of the function. The response.ok check matters too, because fetch only rejects on network failure, not on a 404 or 500.
For larger APIs, a schema library such as Zod builds the same kind of guard from a schema. The principle is the same: data from outside the program is checked, not asserted.
Try the function before any page uses it. Node.js 26 runs .ts files directly by stripping the types, and its fetch accepts data: URLs, so you can feed it a good list and a bad one without a server:
cat > check-bundles.ts <<'TS'
import { loadBundles } from './src/bundles.ts'
const good = 'data:application/json,[{"name":"Weekly 750 MB","mb":750,"days":7,"price":500}]'
const bad = 'data:application/json,[{"name":"Weekly 750 MB","mb":"750"}]'
console.log(await loadBundles(good))
await loadBundles(bad).catch((error: unknown) => {
console.log(error instanceof Error ? error.message : error)
})
TS
node check-bundles.ts
rm check-bundles.tsCheck it worked
The first line printed is the parsed list, [ { name: 'Weekly 750 MB', mb: 750, days: 7, price: 500 } ]. The second starts with Not a list of bundles:, because mb was a string and days and price were missing. Run npx tsc --noEmit again: there are still errors in src/main.ts, and none in src/bundles.ts.
Step 6 · Type the event handlers
Now rewrite main.ts to use the checked elements and the checked loader. The logic is unchanged; what changes is that every value has a known type:
cat > src/main.ts <<'TS'
import { form, dailyInput, daysSelect, checkButton, resetButton, result } from './elements.ts'
import { loadBundles, type Bundle } from './bundles.ts'
let bundles: Bundle[] = []
function cheapestFor(neededMb: number, days: number): Bundle | undefined {
return bundles
.filter((bundle) => bundle.mb >= neededMb && bundle.days >= days)
.sort((a, b) => a.price - b.price)
.at(0)
}
// Inline handler: TypeScript knows a 'submit' listener receives a SubmitEvent.
form.addEventListener('submit', (event) => {
event.preventDefault()
const days = Number(daysSelect.value)
const needed = dailyInput.valueAsNumber * days
const best = cheapestFor(needed, days)
result.textContent = best
? `${best.name} covers ${needed} MB over ${days} days for ${best.price} credit.`
: `No single bundle covers ${needed} MB. Try a shorter period.`
})
function handleReset(): void {
form.reset()
result.textContent = ''
}
resetButton.addEventListener('click', handleReset)
// Named handler: you choose the event type, and currentTarget is only an EventTarget.
function clearResult(event: Event): void {
if (event.currentTarget instanceof HTMLInputElement || event.currentTarget instanceof HTMLSelectElement) {
result.textContent = ''
}
}
dailyInput.addEventListener('input', clearResult)
daysSelect.addEventListener('change', clearResult)
loadBundles('/bundles.json')
.then((list) => {
bundles = list
checkButton.disabled = false
})
.catch((error: unknown) => {
console.error(error)
result.textContent = 'Bundle prices could not be loaded. Check your connection and reload the page.'
})
TS
npx tsc --noEmitHow the handlers get their types:
- Inline handlers are inferred.
addEventListener('submit', ...)looks up'submit'in the DOM lib's event map, soeventis aSubmitEventwithout an annotation. A'click'listener gets aMouseEvent,'keydown'aKeyboardEvent. - Named handlers need an annotation, because a function declared on its own does not know where it will be attached.
clearResulttakes a plainEventso it can serve both the input and the select. event.currentTargetandevent.targetareEventTarget | null, not elements. A shared handler narrows them withinstanceofbefore touching element properties, the same as withquerySelector.- A handler that ignores the event can leave the parameter out, as
handleResetdoes. TypeScript allows a function with fewer parameters wherever more are passed.
The compiler also catches a handler attached to the wrong event. A function declared as (event: KeyboardEvent) => void and passed to a 'click' listener fails with TS2769: No overload matches this call, because a click does not carry event.key.
.at(0) returns Bundle | undefined, which is the truth about an empty filter result, and the best ? ... : ... branch handles it. The old [0] claimed to return a Bundle even when the list was empty. The .catch takes error: unknown, the only honest type for something thrown, and shows readers a message they can act on instead of a page that never enables its button.
Check it worked
npx tsc --noEmit prints nothing and exits with status 0: all 16 errors are gone, and the files in src/ contain no as casts and no non-null !.
Step 7 · Run the type check in CI
Vite does not type-check while it serves or bundles; it only removes the types. The template's build script runs tsc && vite build for that reason, but a dedicated script lets CI check types without building. Add one:
npm pkg set scripts.typecheck="tsc --noEmit"
npm run typecheckThen add a GitHub Actions workflow that runs it on every push and pull request. npm ci installs exactly what package-lock.json records, so CI uses the same TypeScript 7 version as your machine:
mkdir -p .github/workflows
cat > .github/workflows/typecheck.yml <<'YAML'
name: Type check
on:
push:
pull_request:
jobs:
typecheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 26
cache: npm
- run: npm ci
- run: npm run typecheck
YAML
npm ci
npm run typecheckProve that the check fails when it should. Add a file with a deliberate mistake, run the script, then remove the file:
echo 'export const total: number = "1050 MB"' > src/oops.ts
npm run typecheck || echo "typecheck failed with status $?"
rm src/oops.tsOnce the project is in a GitHub repository, mark the Type check job as a required status check in the branch protection settings, so a pull request with type errors cannot be merged.
Check it worked
The first npm run typecheck prints the > tsc --noEmit line and no errors. The run with src/oops.ts prints error TS2322: Type 'string' is not assignable to type 'number'. and then typecheck failed with status with a non-zero number. After you push the project to GitHub, the Actions tab shows a Type check run with a green tick.
Step 8 · Test the finished page in a browser
The compiler proves the types line up. It cannot prove the page works, that the ids in the HTML match elements.ts, or that a broken price list really shows the error message. Build the site, which runs the type check first:
npm run build
ls distStart the preview server, which serves dist/ at http://localhost:4173/, and leave it running. Open that address in your browser and try a few amounts, then open a second terminal in ~/ts-dom-demo for the rest of this step:
npm run previewInstall Playwright and Chromium. On Linux, --with-deps also installs the system libraries Chromium needs and may ask for your password:
npm install --save-dev playwright@1.65.1
npx playwright install --with-deps chromiumWrite a test that uses the page like a visitor on a small phone screen, then serves a malformed price list to check that the runtime guard catches it:
cat > check-page.mjs <<'JS'
import { chromium } from 'playwright'
import assert from 'node:assert/strict'
const site = 'http://localhost:4173/'
const browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 360, height: 740 } })
// Collect uncaught errors and failed requests.
const pageErrors = []
const failed = []
page.on('pageerror', (error) => pageErrors.push(error.message))
page.on('response', (r) => { if (r.status() >= 400) failed.push(`${r.status()} ${r.url()}`) })
await page.goto(site)
// The button is enabled once the bundle list has loaded and passed the check.
const findButton = page.getByRole('button', { name: 'Find a bundle' })
await page.waitForFunction(() => !document.querySelector('#check')?.hasAttribute('disabled'))
const result = page.locator('#result')
// 150 MB a day for 7 days is 1050 MB: Weekly 1.5 GB is the cheapest that covers it.
await page.getByLabel('Data you use a day (MB)').fill('150')
await page.getByLabel('How long you need it for').selectOption('7')
await findButton.click()
assert.equal(await result.textContent(), 'Weekly 1.5 GB covers 1050 MB over 7 days for 1000 credit.')
// Changing a field clears the old answer.
await page.getByLabel('Data you use a day (MB)').fill('500')
assert.equal(await result.textContent(), '')
// 500 MB a day for 30 days is more than any bundle.
await page.getByLabel('How long you need it for').selectOption('30')
await findButton.click()
assert.equal(await result.textContent(), 'No single bundle covers 15000 MB. Try a shorter period.')
// Start again puts the form back to its defaults.
await page.getByRole('button', { name: 'Start again' }).click()
assert.equal(await page.getByLabel('Data you use a day (MB)').inputValue(), '150')
assert.equal(await result.textContent(), '')
assert.deepEqual(pageErrors, [], 'no uncaught errors')
assert.deepEqual(failed, [], 'no failed requests')
// A bundle list with the wrong shape is caught, not used.
const broken = await browser.newPage()
await broken.route('**/bundles.json', (route) =>
route.fulfill({ contentType: 'application/json', body: '[{"name":"Weekly 750 MB","mb":"750"}]' }),
)
await broken.goto(site)
await broken.locator('#result').filter({ hasText: 'could not be loaded' }).waitFor()
assert.ok(await broken.getByRole('button', { name: 'Find a bundle' }).isDisabled(), 'button stays disabled')
await browser.close()
console.log('PASS: the typed planner works in Chromium')
JS
node check-page.mjsbroken.route answers the request for bundles.json inside the browser with a list where mb is a string, the kind of mistake a cast would have let through. A visitor on a patchy mobile connection sees the same message if the request fails outright, instead of a button that never works.
Check it worked
The last line of output is PASS: the typed planner works in Chromium. In your browser at http://localhost:4173/, entering 150 and 7 days shows Weekly 1.5 GB covers 1050 MB over 7 days for 1000 credit.
Step 9 · Clean up
Stop the preview server with Ctrl+C in its terminal. Then delete the project, which also removes the local Playwright package. The Chromium browser Playwright downloaded stays in a shared cache; run npx playwright uninstall from the project folder first if you want that gone too.
cd ~
rm -rf ~/ts-dom-demoCheck it worked
ls ~/ts-dom-demo reports that there is no such file or directory, and http://localhost:4173/ no longer loads.
Next steps
- Go back over the DOM methods this tutorial typed, in plain JavaScript, with select and change page elements with the DOM.
- Read every
tsconfig.jsonoption used here, and the rest, in set up a TypeScript 7 project. - Test
cheapestForand the type guard without a browser in test UI code with Vitest and Testing Library. - See what Vite does with the rest of a project in start a plain JavaScript project with Vite.
Part of these paths
Related tutorials
- How to Set Up a TypeScript 7 Project from ScratchYou will create a Node.js 26 project, install TypeScript 7, write a tsconfig.json you understand, compile two files to JavaScript, watch the compiler catch a type error, and add npm scripts for building, checking and running.
- Hello World in TypeScript: catch a type error before it runsYou will install TypeScript 7 in a throwaway folder, compile and run a typed Hello World on Node.js 26, watch the compiler reject a wrong argument, and run the same file directly with Node's built-in type stripping.
- Select and change page elements with the DOMYou will build a reading-list page whose script finds, changes, adds and removes elements, then renders the whole list from an array through a template and re-renders it when the array changes.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials