Command Palette

Search for a command to run...

Hectal
Phase 13Intermediate14 of 18 in TypeScript

TypeScript in the Browser: DOM and Async

Type the page you work with: DOM elements and events, promises and async code, data from fetch, errors, and browser storage, all checked by the compiler.

Most TypeScript you write for the web touches things that TypeScript did not create: the DOM (the tree of elements the browser builds from your HTML), events, promises, network responses and storage. This phase shows how TypeScript describes each of them, and where it can only take your word for it.

You'll learn to read Element | null without fear, to tell a harmless cast from a lie, to type events and your own custom events, to follow what a promise really returns, and to treat data from the network as unknown until a runtime check proves what it is.

Every example runs with a real page next to it. The Types panel shows what tsc says about your code, and the page and the Console show what it does. Phase 14 builds on this with React.

0/6 · 0%
6 topics ~2 h 25 code blocks & diagrams
Start with the first topic
1
13.1

Typing the DOM

The DOM is the tree of elements a browser builds from your HTML. TypeScript describes every kind of element with its own type, and because a lookup can fail, the answer is often Element | null and you must handle the null.

20 min 4 code practice

2
13.2

Typing Events

When you call addEventListener with a known event name, TypeScript looks the name up in an event map and gives your handler the exact event type, so click gives mouse details and keydown gives the key. Custom events can be typed with CustomEvent<T>.

20 min 4 code practice

3
13.3

Promises and async/await

A Promise<T> is a value that will arrive later. TypeScript tracks what it will hold, turns every async function's return into a Promise, unwraps with await and Awaited, and treats a caught error as unknown.

20 min 5 code practice

4
13.4

Fetching Data Safely

Data from a network is outside TypeScript's reach: response.json() returns any, and declaring a type on it is a promise nobody checks. Treat it as unknown, check it at runtime with a validator, and let a schema give you the type.

23 min 4 code practice

5
13.5

Typed Error Handling

TypeScript can't say what a function throws, so errors need a plan: subclasses of Error you can tell apart with instanceof, a Result<T, E> union that makes failure part of the return type, cause to keep the original error, and using to clean up reliably.

21 min 4 code practice

6
13.6

Typing Browser Storage and APIs

Browser storage keeps only text, so everything you read back is untrusted. Learn typed wrappers around localStorage, safe JSON.parse, URLSearchParams, structuredClone, and how to build a small typed store.

22 min 4 code practice

Practise this phase

Hands-on exercises: write the code, see your page live, and press Check to have it tested automatically.