This is a practical, step-by-step guide to building a small web app with TypeScript, without a framework or a bundler. By the end you'll have a working reading list app that saves its data, imports and exports files and has its own tests, and you'll have used the parts of TypeScript that matter most in everyday web development.
If you're new to TypeScript, my introduction to TypeScript explains what it is and why it's worth learning. If you're coming from PHP, TypeScript for PHP developers covers the differences you'll notice first.
What you'll build
The app is a reading list. You can:
- add books, with an optional author
- move each book through "To read", "Reading" and "Finished"
- filter the list by status
- remove books
- keep the list between visits, using the browser's
localStorage - export the list to a file and import it again, for example to move it to another browser
It's deliberately small, but it covers what most basic web apps need to do: handle a form, update the page, store data, read files and deal with data you can't trust.
Why TypeScript, and why no framework
TypeScript's main benefit is that it checks your code before anyone runs it. Here's a line most of us have written in JavaScript:
const input = document.querySelector("#title");
console.log(input.value);
TypeScript finds two problems straight away:
error TS18047: 'input' is possibly 'null'.
error TS2339: Property 'value' does not exist on type 'Element'.
querySelector returns null when nothing matches, so this breaks the moment the field is renamed. And TypeScript can't know the element is an <input>, so it can't promise it has a value. You'll see how to deal with both properly below.
You don't need React, Vue or a bundler to get these benefits. For a small app, the TypeScript compiler and a few lines of configuration are enough, and building without a framework is the best way to understand what TypeScript itself is doing. Everything here carries over when you do move to a framework.
Setting up the project
You need a recent version of Node.js (22.18 or later, for the tests) and a code editor. VS Code has TypeScript support built in, so errors appear as you type.
Create a folder and install TypeScript:
mkdir reading-list
cd reading-list
npm init -y
npm install --save-dev typescript
This installs TypeScript 7, the version with the much faster compiler written in Go. It checks code exactly as earlier versions did, so nothing here depends on it.
The TypeScript configuration
Create a tsconfig.json file. Running npx tsc --init creates a long one full of comments, but this is all the app needs:
{
"compilerOptions": {
"target": "es2022",
"lib": ["es2022", "dom"],
"module": "esnext",
"moduleResolution": "bundler",
"rootDir": "src",
"outDir": "dist",
"rewriteRelativeImportExtensions": true,
"erasableSyntaxOnly": true,
"strict": true,
"noEmitOnError": true,
"sourceMap": true
},
"include": ["src"]
}
What each setting does:
targetandlib: output modern JavaScript, and include the type definitions for the browser (dom), so TypeScript knows aboutdocument,localStorageand the rest.moduleandmoduleResolution: keepimportandexportas they are, so the browser can load the files as ES modules without a bundler.rootDirandoutDir: your TypeScript lives insrc/, and the compiled JavaScript goes intodist/.rewriteRelativeImportExtensions: lets you import files by their real names, such as./books.ts, and changes them to./books.jsin the compiled output. That way the same imports work in the browser after compiling and in Node.js when running the tests.erasableSyntaxOnly: only allows TypeScript features that can be removed without generating extra JavaScript. That's what lets Node.js run the files directly, and it rules out a couple of older features, such asenum, that you won't miss.strict: turns on the most useful checks, including thenullcheck above. It's the default anyway, but I set it explicitly so nobody has to wonder.noEmitOnError: by default,tscstill writes the JavaScript when there are errors. This stops it, so a broken build can't quietly end up indist/.sourceMap: lets the browser's developer tools show your TypeScript when you're debugging.
Scripts
Update package.json so it looks like this:
{
"name": "reading-list",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"build": "tsc",
"watch": "tsc --watch",
"test": "node --test"
},
"devDependencies": {
"typescript": "^7.0.2"
}
}
"type": "module" tells Node.js that the project uses import and export, which the tests need. The three scripts compile the app once, compile it every time you save, and run the tests.
The project structure
When it's finished, the project looks like this:
reading-list/
├── index.html
├── package.json
├── tsconfig.json
├── src/
│ ├── books.ts the app's logic, with no DOM code
│ ├── main.ts connects the logic to the page
│ ├── storage.ts saving and loading
│ └── types.ts the shape of the data
├── tests/
│ └── books.test.ts
└── dist/ created by the compiler
Keeping the logic in books.ts separate from the page code in main.ts is the most useful habit in this guide. Code that doesn't touch the DOM is easy to test and easy to reuse.
The HTML
<!doctype html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Reading list</title>
<script type="module" src="dist/main.js"></script>
</head>
<body>
<main>
<h1>Reading list</h1>
<form id="add-book">
<label for="title">Title</label>
<input id="title" name="title" required>
<label for="author">Author (optional)</label>
<input id="author" name="author">
<button type="submit">Add book</button>
</form>
<label for="filter">Show</label>
<select id="filter">
<option value="all">All books</option>
<option value="to-read">To read</option>
<option value="reading">Reading</option>
<option value="finished">Finished</option>
</select>
<ul id="books"></ul>
<p id="message" role="status"></p>
<button type="button" id="export">Export list</button>
<label for="import">Import a list</label>
<input type="file" id="import" accept="application/json,.json">
</main>
</body>
</html>
A few things to note:
- The script points at the compiled
dist/main.js, not the TypeScript file. type="module"lets the script useimport. Module scripts also wait until the page has loaded before running, so it's safe in the<head>.- The message paragraph has
role="status", so screen readers announce updates such as "Added Piranesi." without moving the visitor's focus.
Describing the data
Start with the types, in src/types.ts:
export const statuses = ["to-read", "reading", "finished"] as const;
export type Status = (typeof statuses)[number];
export interface Book {
id: string;
title: string;
author?: string;
status: Status;
}
export type Filter = Status | "all";
This short file does a lot.
statusesis the single source of truth.as consttells TypeScript to treat the array as a fixed list of those exact strings, rather than any oldstring[].Statusis worked out from it.(typeof statuses)[number]means "any value in that array", which comes out as"to-read" | "reading" | "finished". Add a status to the array and the type updates itself.Bookis an interface describing every book. The?onauthormakes it optional: a book may or may not have one, and TypeScript makes you check before using it.Filteris either a status or"all", which is everything the filter drop-down can be set to.
Types like these are where TypeScript starts to pay off. Use a status that doesn't exist anywhere in the app and you get an error rather than a book with a blank button:
error TS2322: Type '"done"' is not assignable to type 'Status'.
The app's logic
Next, src/books.ts holds everything the app does with books, without touching the page:
import { statuses, type Book, type Filter, type Status } from "./types.ts";
const nextStatuses: Record<Status, Status> = {
"to-read": "reading",
reading: "finished",
finished: "to-read",
};
export function createBook(title: string, author = ""): Book {
const book: Book = {
id: crypto.randomUUID(),
title: title.trim(),
status: "to-read",
};
if (author.trim() !== "") book.author = author.trim();
return book;
}
export function nextStatus(status: Status): Status {
return nextStatuses[status];
}
export function filterBooks(books: Book[], filter: Filter): Book[] {
return filter === "all" ? books : books.filter((book) => book.status === filter);
}
export function isStatus(value: unknown): value is Status {
return statuses.some((status) => status === value);
}
export function isBook(value: unknown): value is Book {
if (typeof value !== "object" || value === null) return false;
const book = value as Record<string, unknown>;
return (
typeof book.id === "string" &&
typeof book.title === "string" &&
(book.author === undefined || typeof book.author === "string") &&
isStatus(book.status)
);
}
export function parseBooks(json: string): Book[] {
const data: unknown = JSON.parse(json);
if (!Array.isArray(data)) throw new Error("Expected a list of books.");
return data.filter(isBook);
}
Going through it:
import { statuses, type Book, ... }brings in both a value (statuses) and types. Thetypekeyword marks the ones that only exist for the compiler, so they're removed from the output.Recordobjects check themselves.Record<Status, Status>means "an object with an entry for every status".nextStatuseshere, andlabelsinmain.ts, must cover every status. Leave one out, or add a fourth status later, and TypeScript tells you exactly what's missing:
error TS2741: Property 'finished' is missing in type '{ "to-read": string; reading: string; }' but required in type 'Record<Status, string>'.
createBookonly adds an author if there is one, so books without an author don't end up with an empty string.isStatusandisBookare type guards. Their return type, such asvalue is Book, tells TypeScript that if the function returnstrue, the value really is aBook. You'll use them wherever data comes from outside your code.parseBookstreats the data asunknown.JSON.parsereturnsany, which switches type checking off for everything it touches. Assigning the result tounknownswitches it back on: TypeScript won't let you use the value until you've checked what it is. Anything that isn't a valid book is dropped, and anything that isn't a list at all is rejected with an error.
Saving and loading
src/storage.ts is short, because parseBooks does the hard work:
import { parseBooks } from "./books.ts";
import type { Book } from "./types.ts";
const storageKey = "reading-list";
export function loadBooks(): Book[] {
const saved = localStorage.getItem(storageKey);
if (saved === null) return [];
try {
return parseBooks(saved);
} catch {
return [];
}
}
export function saveBooks(books: Book[]): void {
localStorage.setItem(storageKey, JSON.stringify(books));
}
The saved data could have been edited by hand, damaged, or saved by an older version of the app in a different format. If it can't be read at all, the app starts with an empty list rather than breaking.
Connecting it to the page
Finally, src/main.ts connects the logic to the HTML:
import { createBook, filterBooks, isStatus, nextStatus, parseBooks } from "./books.ts";
import { loadBooks, saveBooks } from "./storage.ts";
import type { Book, Filter, Status } from "./types.ts";
function getElement<T extends Element>(selector: string): T {
const element = document.querySelector<T>(selector);
if (element === null) throw new Error(`Missing element: ${selector}`);
return element;
}
const form = getElement<HTMLFormElement>("#add-book");
const titleInput = getElement<HTMLInputElement>("#title");
const authorInput = getElement<HTMLInputElement>("#author");
const filterSelect = getElement<HTMLSelectElement>("#filter");
const list = getElement<HTMLUListElement>("#books");
const exportButton = getElement<HTMLButtonElement>("#export");
const importInput = getElement<HTMLInputElement>("#import");
const message = getElement<HTMLParagraphElement>("#message");
const labels: Record<Status, string> = {
"to-read": "To read",
reading: "Reading",
finished: "Finished",
};
let books: Book[] = loadBooks();
let filter: Filter = "all";
function update(): void {
saveBooks(books);
const visible = filterBooks(books, filter);
if (visible.length === 0) {
const empty = document.createElement("li");
empty.textContent = books.length === 0 ? "No books yet." : "No books match this filter.";
list.replaceChildren(empty);
} else {
list.replaceChildren(...visible.map(renderBook));
}
}
function showMessage(text: string): void {
message.textContent = text;
}
function renderBook(book: Book): HTMLLIElement {
const item = document.createElement("li");
const title = document.createElement("span");
title.textContent = book.author ? `${book.title} by ${book.author}` : book.title;
const statusButton = document.createElement("button");
statusButton.type = "button";
statusButton.textContent = labels[book.status];
statusButton.addEventListener("click", () => {
book.status = nextStatus(book.status);
update();
});
const removeButton = document.createElement("button");
removeButton.type = "button";
removeButton.textContent = "Remove";
removeButton.addEventListener("click", () => {
books = books.filter((other) => other.id !== book.id);
update();
showMessage(`Removed ${book.title}.`);
});
item.append(title, statusButton, removeButton);
return item;
}
form.addEventListener("submit", (event) => {
event.preventDefault();
if (titleInput.value.trim() === "") return;
const book = createBook(titleInput.value, authorInput.value);
books.push(book);
form.reset();
titleInput.focus();
update();
showMessage(`Added ${book.title}.`);
});
filterSelect.addEventListener("change", () => {
const value = filterSelect.value;
if (value === "all" || isStatus(value)) {
filter = value;
update();
}
});
exportButton.addEventListener("click", () => {
const file = new Blob([JSON.stringify(books, null, 2)], { type: "application/json" });
const link = document.createElement("a");
link.href = URL.createObjectURL(file);
link.download = "reading-list.json";
link.click();
URL.revokeObjectURL(link.href);
});
importInput.addEventListener("change", async () => {
const file = importInput.files?.[0];
if (file === undefined) return;
try {
books = parseBooks(await file.text());
update();
showMessage(`Imported ${books.length} ${books.length === 1 ? "book" : "books"}.`);
} catch (error) {
showMessage(error instanceof SyntaxError ? "That file isn't valid JSON." : String(error));
} finally {
importInput.value = "";
}
});
update();
The parts worth understanding:
Finding elements safely
getElement fixes both errors from the start of this guide. The <T extends Element> part makes it generic: you say which kind of element you expect, such as HTMLInputElement, and TypeScript then knows that titleInput.value exists. If an element is missing from the HTML, the script stops straight away with a clear message, rather than failing in a confusing way later on.
Narrowing values from the page
Everything read from a form field is a plain string, so TypeScript won't let you put the filter drop-down's value straight into filter:
error TS2322: Type 'string' is not assignable to type 'Filter'.
The change handler checks it first. After value === "all" || isStatus(value), TypeScript has narrowed the value to Filter, so the assignment is allowed. If someone edits the page and adds an unexpected option, it's simply ignored.
Optional values
book.author might not exist, so the code checks before using it. importInput.files?.[0] uses optional chaining: if there's no file list, the result is undefined rather than an error. Either way, TypeScript won't let you skip the check.
Asynchronous code
Reading a file takes time, so file.text() returns a Promise, and the change handler is an async function that uses await to wait for the result. If you forget the await, TypeScript notices that you've passed a Promise<string> where it expected a string.
Errors are unknown
In strict mode, the error in a catch block is unknown, because JavaScript lets you throw anything, not just Error objects. Checking error instanceof SyntaxError both narrows the type and lets the app show a friendlier message for a file that isn't valid JSON.
Inferred types
Most variables have no type annotations at all. TypeScript works out that visible is a Book[] and that event in the submit handler is a SubmitEvent. As a rule of thumb, add types to function parameters, return values and your data structures, and let TypeScript infer the rest.
Safe output
Book titles and authors are added with textContent rather than innerHTML, so anything typed into the form, or in an imported file, is shown as plain text and can't inject HTML or scripts into the page. That isn't a TypeScript feature, but it matters just as much.
Running the app
Start the compiler in watch mode:
npm run watch
It compiles everything, then recompiles each time you save. Errors appear in the terminal as well as in your editor.
ES modules won't load from a page opened straight from your disk (a file:// address), so you also need a local web server. Any will do, for example:
npx serve .
or python3 -m http.server if you have Python installed. VS Code's Live Preview extension works too. Open the address it gives you, add a few books, reload the page to check they're still there, and try exporting and importing the list.
Debugging
Because sourceMap is on, your browser's developer tools show the original TypeScript files under Sources, and you can set breakpoints in them directly. Error messages in the console point to the line in your .ts file rather than the compiled JavaScript.
Testing
Because the logic lives in books.ts with no DOM code, you can test it without a browser. Node.js 22.18 and later can run TypeScript files directly, and it has a test runner built in, so there's nothing else to install. Create tests/books.test.ts:
import { test } from "node:test";
import assert from "node:assert/strict";
import { createBook, filterBooks, nextStatus, parseBooks } from "../src/books.ts";
test("createBook trims the title and leaves out an empty author", () => {
const book = createBook(" Piranesi ", " ");
assert.equal(book.title, "Piranesi");
assert.equal(book.status, "to-read");
assert.equal("author" in book, false);
});
test("nextStatus cycles through every status", () => {
assert.equal(nextStatus("to-read"), "reading");
assert.equal(nextStatus("reading"), "finished");
assert.equal(nextStatus("finished"), "to-read");
});
test("filterBooks returns only matching books", () => {
const books = [createBook("Piranesi"), createBook("Dune")];
books[1].status = "finished";
assert.deepEqual(filterBooks(books, "finished").map((book) => book.title), ["Dune"]);
assert.equal(filterBooks(books, "all").length, 2);
});
test("parseBooks drops entries that aren't books", () => {
const json = JSON.stringify([
{ id: "1", title: "Piranesi", status: "reading" },
{ id: "2", title: "Dune", status: "done" },
"not a book",
]);
assert.deepEqual(parseBooks(json).map((book) => book.title), ["Piranesi"]);
});
test("parseBooks rejects anything that isn't a list", () => {
assert.throws(() => parseBooks('{"title": "Piranesi"}'), /Expected a list/);
});
Then run:
npm test
Node.js finds files ending in .test.ts automatically and runs them:
# tests 5
# pass 5
# fail 0
One thing to know: Node.js runs TypeScript by stripping the types out, without checking them. The tsconfig.json above only checks src/, so if you'd like the tests type-checked as well, install @types/node and give the tests a small tsconfig.json of their own. For larger projects, Vitest is a popular test runner that works the same way.
Deploying
Run npm run build, then upload index.html and the dist folder to any static host. With Netlify, you can drag the folder into the dashboard, or connect a Git repository and set npm run build as the build command, so the site rebuilds every time you push. Because noEmitOnError is on, a build with type errors fails rather than publishing broken code.
Habits worth building early
- Avoid
any. It switches off checking for that value and everything it touches. Useunknownand a type guard instead. - Be wary of
as. A type assertion such asvalue as Booktells TypeScript to trust you, and it will, even when you're wrong. Keep them for places where you've just checked the value yourself, asisBookdoes. - Check data at the edges. Anything from outside your code, such as storage, files, APIs and form fields, is a
stringorunknownuntil you've checked it. Once it's inside, the types take care of the rest. - Keep logic away from the DOM. It makes the code easier to test, reuse and move into a framework later.
- Don't silence errors. When TypeScript complains, it's usually right. Fix the code rather than reaching for
anyoras.
When you need more
This setup is fine for small apps. When you want to use packages from npm, have the page reload as you work or bundle everything into fewer files, a build tool such as Vite is the natural next step. Running npm create vite@latest and choosing "Vanilla" and then "TypeScript" gives you a very similar starting point. Vite removes the types without checking them, to keep things fast, so the template's build script runs tsc first to do the checking.
The same TypeScript carries over to frameworks such as React, Vue and Svelte, which all support it, and the habits above apply just as much there.
A quick summary
- Install TypeScript with
npm install --save-dev typescriptand keepstricton. - Describe your data first, ideally from a single source of truth such as the
statusesarray. - Keep your logic separate from the code that updates the page.
- Treat anything from outside your code as
unknown, and check it with type guards. - Run
tsc --watchwhile you work and serve the folder with any local web server. - Test your logic with Node's built-in test runner.
- Build with
noEmitOnError, so type errors can't reach your live site. - Move to Vite or a framework when the app outgrows this setup.
If you'd like a hand with a TypeScript project, or with adding TypeScript to an existing website, take a look at my website development services or get in touch.