Skip to content

Lesson 49 of 50TypeScript

Project: A Typed Expense Tracker

Build the core of a small expense tracker in TypeScript, stage by stage: a typed domain model, a validator for untrusted JSON, pure budget logic, a generic API client and a set of tests, then see the bugs strict mode catches.

15 min read0/5 questions

The to-do project in plain JavaScript showed you state, events and render. This project does the same job for TypeScript. You will build the core of an expense tracker: the part that holds the data, checks it, adds it up and talks to a server. There is no page here, on purpose. The types live in this layer, and it is the layer a team reuses for the web app, the mobile app and the tests.

Each stage below is a complete program in its own runnable block. Every block repeats the code it needs from earlier stages, so you can run any of them alone. They run in a sandbox with a console but no page and no imports, which keeps the focus on the types.

The plan: trust nothing, then trust everything

A tracker gets transactions from outside: a bank export, a form, an API. That data could be anything. Inside your program, though, you want to work with values you never need to check twice. So the design has one rule: data is unknown until a validator says otherwise, and fully typed after that.

Where the types come from
Server: sends JSON textServersends JSON textgetJson<T>: stage 4getJson<T>stage 4parseTransaction: stage 2parseTransactionstage 2Ledger: readonly Transaction[]Ledgerreadonly Transaction[]budgetReport: stage 3budgetReportstage 3You: reads the reportYoureads the reporttextunknownResulttyped datareport

The server sends text. Its types are a promise, not a guarantee.

1/4

Stage 1: the domain model

Start with the nouns. A transaction is an expense, a refund or income, and each kind has different fields. An expense has a category. A refund has a category and points at the expense it refunds. Income has a source. That is a discriminated union, from Unions and Narrowing: a union of object types that share one literal field, here kind, that tells them apart.

Three more choices are worth copying into real projects:

  • Money is whole cents. Floats cannot store most decimal amounts exactly, so 0.1 + 0.2 is not 0.3. Integers can. You format cents as dollars only at the very end.
  • Categories come from one as const array. (typeof CATEGORIES)[number] turns the array into a union of its strings, so the list and the type can never drift apart.
  • Every field is readonly. Once a transaction exists, nothing changes it. Changes make new values instead.
TypeScript
const CATEGORIES = ["food", "transport", "rent", "fun"] as const;type Category = (typeof CATEGORIES)[number]; // "food" | "transport" | "rent" | "fun"type Cents = number; // money as whole cents, never floats interface Expense { readonly kind: "expense"; readonly id: string; readonly date: string; readonly amount: Cents; readonly category: Category;}interface Refund { readonly kind: "refund"; readonly id: string; readonly date: string; readonly amount: Cents; readonly category: Category; readonly refundOf: string;}interface Income { readonly kind: "income"; readonly id: string; readonly date: string; readonly amount: Cents; readonly source: string;}type Transaction = Expense | Refund | Income; function assertNever(value: never): never { throw new Error(`Unhandled case: ${JSON.stringify(value)}`);} // Money in is positive, money out is negative.function signedAmount(tx: Transaction): Cents { switch (tx.kind) { case "expense": return -tx.amount; case "refund": case "income": return tx.amount; default: return assertNever(tx); }} function formatCents(cents: Cents): string { const sign = cents < 0 ? "-" : ""; return `${sign}$${(Math.abs(cents) / 100).toFixed(2)}`;} const BUDGETS = { food: 40000, transport: 9000, rent: 120000, fun: 15000,} satisfies Record<Category, Cents>; const ledger: readonly Transaction[] = [ { kind: "income", id: "t1", date: "2026-10-01", amount: 250000, source: "Salary" }, { kind: "expense", id: "t2", date: "2026-10-01", amount: 120000, category: "rent" }, { kind: "expense", id: "t3", date: "2026-10-03", amount: 4250, category: "food" }, { kind: "refund", id: "t4", date: "2026-10-05", amount: 1500, category: "food", refundOf: "t3" },]; const balance = ledger.reduce((sum, tx) => sum + signedAmount(tx), 0);console.log("Balance:", formatCents(balance));console.log("Food budget:", formatCents(BUDGETS.food));for (const tx of ledger) console.log(tx.id, tx.kind, formatCents(signedAmount(tx)));
Output
Press Run (⌘ Enter) to see what happens.

Look at signedAmount. The switch on tx.kind narrows tx in each branch, so tx.amount is always safe. The default branch passes tx to assertNever, which only accepts never. When every kind is handled, tx really is never there, and the code compiles. Add a fourth kind to the union and forget a case, and tx becomes that new type in default. That line stops compiling, and the compiler points you at every switch you need to update.

Now look at BUDGETS. It uses satisfies Record<Category, Cents>, which you met in Utility Types and Advanced Types. The check is real: leave out fun or misspell food and it fails. But unlike a type annotation, satisfies keeps the object's own, more precise type, so BUDGETS.food stays a known key instead of any string.

Quick check
You add a Transfer type, with its own kind literal, to the Transaction union but do not touch signedAmount. What happens?
Need a nudge? A hint rules out a wrong answer.
Predict the outputTypeScript

What does this print?

type Tx = { kind: "income" | "expense" | "refund"; amount: number };
const txs: Tx[] = [
{ kind: "income", amount: 250000 },
{ kind: "expense", amount: 120000 },
{ kind: "refund", amount: 1500 },
{ kind: "expense", amount: 4250 },
];
const balance = txs.reduce((sum, tx) => sum + (tx.kind === "expense" ? -tx.amount : tx.amount), 0);
console.log((balance / 100).toFixed(2));
Need a nudge? Hints walk you through it.

Stage 2: a validator at the edge

Your types say what a transaction looks like. They say nothing about the JSON that arrives. As Type Safety in Practice put it, the network erases types. So the parser takes unknown and returns a Result, a small generic type from Generics:

type Result<T, E = string> = { ok: true; value: T } | { ok: false; error: E };

Result is itself a discriminated union, on ok. A caller has to check result.ok before it can reach value, so it cannot forget that parsing might fail. Compare that with a function that throws: nothing in its type tells you to catch.

The parser is built from type guards, functions whose return type is value is Something. When isCategory(raw.category) returns true, TypeScript treats raw.category as a Category from then on. Each check narrows one field, and by the time you call ok(...), every field has a proven type. If you forget one, the object you pass to ok does not match Transaction, and it fails to compile.

TypeScript
// The model from stage 1, written compactly.const CATEGORIES = ["food", "transport", "rent", "fun"] as const;type Category = (typeof CATEGORIES)[number];type Cents = number; interface Expense { readonly kind: "expense"; readonly id: string; readonly date: string; readonly amount: Cents; readonly category: Category }interface Refund { readonly kind: "refund"; readonly id: string; readonly date: string; readonly amount: Cents; readonly category: Category; readonly refundOf: string }interface Income { readonly kind: "income"; readonly id: string; readonly date: string; readonly amount: Cents; readonly source: string }type Transaction = Expense | Refund | Income; type Result<T, E = string> = { ok: true; value: T } | { ok: false; error: E };function ok<T>(value: T): { ok: true; value: T } { return { ok: true, value };}function err<E>(error: E): { ok: false; error: E } { return { ok: false, error };} // Type guards: runtime checks the compiler understands.function isRecord(value: unknown): value is Record<string, unknown> { return typeof value === "object" && value !== null && !Array.isArray(value);}function isCategory(value: unknown): value is Category { return typeof value === "string" && (CATEGORIES as readonly string[]).includes(value);} function parseTransaction(raw: unknown): Result<Transaction> { if (!isRecord(raw)) return err("not an object"); const { kind, id, date, amount } = raw; if (typeof id !== "string" || id === "") return err("id must be a non-empty string"); if (typeof date !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(date)) return err(`${id}: date must be YYYY-MM-DD`); if (typeof amount !== "number" || !Number.isInteger(amount) || amount <= 0) { return err(`${id}: amount must be a positive whole number of cents`); } switch (kind) { case "expense": if (!isCategory(raw.category)) return err(`${id}: unknown category`); return ok({ kind, id, date, amount, category: raw.category }); case "refund": if (!isCategory(raw.category)) return err(`${id}: unknown category`); if (typeof raw.refundOf !== "string") return err(`${id}: refundOf must be a string`); return ok({ kind, id, date, amount, category: raw.category, refundOf: raw.refundOf }); case "income": if (typeof raw.source !== "string") return err(`${id}: source must be a string`); return ok({ kind, id, date, amount, source: raw.source }); default: return err(`${id}: unknown kind ${JSON.stringify(kind)}`); }} // Pretend this text came from a file upload or a server.const body = `[ { "kind": "income", "id": "t1", "date": "2026-10-01", "amount": 250000, "source": "Salary" }, { "kind": "expense", "id": "t2", "date": "2026-10-03", "amount": 4250, "category": "food" }, { "kind": "expense", "id": "t3", "date": "2026-10-04", "amount": "12.00", "category": "food" }, { "kind": "expense", "id": "t4", "date": "2026-10-06", "amount": 900, "category": "snacks" }, { "kind": "transfer", "id": "t5", "date": "2026-10-07", "amount": 5000 }]`; const data: unknown = JSON.parse(body);const rows = Array.isArray(data) ? data : [];const good: Transaction[] = [];for (const row of rows) { const result = parseTransaction(row); if (result.ok) good.push(result.value); else console.log("Rejected:", result.error);}console.log(`Accepted ${good.length} of ${rows.length}:`, good.map((tx) => tx.id).join(", "));
Output
Press Run (⌘ Enter) to see what happens.

Run it. Two rows are kept and three are turned away, each with a reason you could show a user: an amount sent as a string, a category that does not exist, a kind the app does not know. Nothing crashed, and no bad value reached the ledger. Try changing "snacks" to "fun" and run it again.

Where Zod fits

Writing guards by hand is fine for a few types, and it is good to have done once, because it shows you exactly what a validator does. In a real codebase you would usually describe the shape once with a schema library like Zod, as End-to-End Type Safety showed, and get the type for free:

import { z } from "zod";
 
const Category = z.enum(["food", "transport", "rent", "fun"]);
const Base = { id: z.string().min(1), date: z.iso.date(), amount: z.number().int().positive() };
 
const Transaction = z.discriminatedUnion("kind", [
  z.object({ kind: z.literal("expense"), ...Base, category: Category }),
  z.object({ kind: z.literal("refund"), ...Base, category: Category, refundOf: z.string() }),
  z.object({ kind: z.literal("income"), ...Base, source: z.string() }),
]);
type Transaction = z.infer<typeof Transaction>;
 
const result = Transaction.safeParse(raw); // { success: true, data } or { success: false, error }

The idea is the same: unknown in, a typed value or an error out. safeParse is Zod's version of your Result. The schema replaces the guards and the hand-written interfaces, so they can never disagree. The rule does not change either way: validate once, at the edge.

Stage 3: pure budget logic

Now the part users care about: how much did I spend, and am I over budget? This is plain logic, so write it as pure functions. They take the ledger and return a new value. They do not log, fetch or change their inputs. Pure functions are easy to test and easy to trust, and stage 5 relies on that.

This stage also puts the built-ins from Utility Types to work:

  • Record<Category, Cents> is an object with exactly one number per category. Add a category to CATEGORIES and every place that builds one fails to compile until you add the new key.
  • Omit<Expense, "kind" | "id"> is the shape a form sends: the user picks a date, amount and category, and the app fills in the rest. You derive it from Expense, so it follows any change to the model.
  • Readonly<...> and readonly Transaction[] mean these functions cannot change what you give them. ledger.push(...) does not compile on a readonly array.
TypeScript
// The model from stage 1, written compactly.const CATEGORIES = ["food", "transport", "rent", "fun"] as const;type Category = (typeof CATEGORIES)[number];type Cents = number; interface Expense { readonly kind: "expense"; readonly id: string; readonly date: string; readonly amount: Cents; readonly category: Category }interface Refund { readonly kind: "refund"; readonly id: string; readonly date: string; readonly amount: Cents; readonly category: Category; readonly refundOf: string }interface Income { readonly kind: "income"; readonly id: string; readonly date: string; readonly amount: Cents; readonly source: string }type Transaction = Expense | Refund | Income; function assertNever(value: never): never { throw new Error(`Unhandled case: ${JSON.stringify(value)}`);}function formatCents(cents: Cents): string { const sign = cents < 0 ? "-" : ""; return `${sign}$${(Math.abs(cents) / 100).toFixed(2)}`;} type CategoryTotals = Record<Category, Cents>;type NewExpense = Omit<Expense, "kind" | "id">; // what a form sends: no kind, no id yettype BudgetLine = Readonly<{ category: Category; spent: Cents; budget: Cents; over: boolean }>; // Pure: same input, same output, no side effects.function addExpense(ledger: readonly Transaction[], input: NewExpense, id: string): readonly Transaction[] { return [...ledger, { kind: "expense", id, ...input }];} function spendByCategory(ledger: readonly Transaction[]): CategoryTotals { const totals: CategoryTotals = { food: 0, transport: 0, rent: 0, fun: 0 }; for (const tx of ledger) { switch (tx.kind) { case "expense": totals[tx.category] += tx.amount; break; case "refund": totals[tx.category] -= tx.amount; break; case "income": break; // income is not spending default: assertNever(tx); } } return totals;} function budgetReport(ledger: readonly Transaction[], budgets: Readonly<CategoryTotals>): BudgetLine[] { const spent = spendByCategory(ledger); return CATEGORIES.map((category) => ({ category, spent: spent[category], budget: budgets[category], over: spent[category] > budgets[category], }));} const BUDGETS = { food: 40000, transport: 9000, rent: 120000, fun: 15000 } satisfies CategoryTotals; let ledger: readonly Transaction[] = [ { kind: "income", id: "t1", date: "2026-10-01", amount: 250000, source: "Salary" }, { kind: "expense", id: "t2", date: "2026-10-01", amount: 120000, category: "rent" }, { kind: "expense", id: "t3", date: "2026-10-03", amount: 4250, category: "food" }, { kind: "refund", id: "t4", date: "2026-10-05", amount: 1500, category: "food", refundOf: "t3" },];ledger = addExpense(ledger, { date: "2026-10-08", amount: 16000, category: "fun" }, "t5");// ledger.push(...) would not compile: readonly arrays have no push. for (const line of budgetReport(ledger, BUDGETS)) { const flag = line.over ? "OVER" : "ok"; console.log(`${line.category.padEnd(10)} ${formatCents(line.spent).padStart(9)} of ${formatCents(line.budget).padStart(9)} ${flag}`);}
Output
Press Run (⌘ Enter) to see what happens.

addExpense builds a new array with spread instead of pushing, the same immutable update you used in the to-do app. spendByCategory uses the exhaustive switch again, so a new transaction kind has to decide whether it counts as spending. And budgetReport maps over CATEGORIES, so the report always has one line per category in a fixed order.

Fun spending is over budget in this run. Change the 16000 to 12000 and the flag goes away.

Match the pairs0/5 matched

Match each piece of the tracker to the job it does.

Choose an item, then its match on the other side.

Stage 4: a typed API client

Real transactions come from a server. You could call fetch in every function that needs data, but then every caller would repeat the same steps: send the request, check the status, parse the text, validate the shape and handle each failure. Put those steps in one generic function, getJson<T>, and give it two inputs:

  • A parser, (raw: unknown) => Result<T>. The parser decides what T is, so the caller gets a typed value without a single cast.
  • A transport, a function from a path to a raw response. In the app it wraps fetch. Here it is a fake that returns canned responses, which is also exactly what a test needs.

Failures are a union too. ApiError has three kinds: the network failed, the server answered with an error status, or the data was invalid. These need different messages and different fixes, so they are different types, and describeError handles each one with an exhaustive switch.

TypeScript
// The model from stage 1, written compactly.const CATEGORIES = ["food", "transport", "rent", "fun"] as const;type Category = (typeof CATEGORIES)[number];type Cents = number; interface Expense { readonly kind: "expense"; readonly id: string; readonly date: string; readonly amount: Cents; readonly category: Category }interface Refund { readonly kind: "refund"; readonly id: string; readonly date: string; readonly amount: Cents; readonly category: Category; readonly refundOf: string }interface Income { readonly kind: "income"; readonly id: string; readonly date: string; readonly amount: Cents; readonly source: string }type Transaction = Expense | Refund | Income; type Result<T, E = string> = { ok: true; value: T } | { ok: false; error: E };function ok<T>(value: T): { ok: true; value: T } { return { ok: true, value };}function err<E>(error: E): { ok: false; error: E } { return { ok: false, error };} function assertNever(value: never): never { throw new Error(`Unhandled case: ${JSON.stringify(value)}`);}function formatCents(cents: Cents): string { const sign = cents < 0 ? "-" : ""; return `${sign}$${(Math.abs(cents) / 100).toFixed(2)}`;} // Type guards: runtime checks the compiler understands.function isRecord(value: unknown): value is Record<string, unknown> { return typeof value === "object" && value !== null && !Array.isArray(value);}function isCategory(value: unknown): value is Category { return typeof value === "string" && (CATEGORIES as readonly string[]).includes(value);} function parseTransaction(raw: unknown): Result<Transaction> { if (!isRecord(raw)) return err("not an object"); const { kind, id, date, amount } = raw; if (typeof id !== "string" || id === "") return err("id must be a non-empty string"); if (typeof date !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(date)) return err(`${id}: date must be YYYY-MM-DD`); if (typeof amount !== "number" || !Number.isInteger(amount) || amount <= 0) { return err(`${id}: amount must be a positive whole number of cents`); } switch (kind) { case "expense": if (!isCategory(raw.category)) return err(`${id}: unknown category`); return ok({ kind, id, date, amount, category: raw.category }); case "refund": if (!isCategory(raw.category)) return err(`${id}: unknown category`); if (typeof raw.refundOf !== "string") return err(`${id}: refundOf must be a string`); return ok({ kind, id, date, amount, category: raw.category, refundOf: raw.refundOf }); case "income": if (typeof raw.source !== "string") return err(`${id}: source must be a string`); return ok({ kind, id, date, amount, source: raw.source }); default: return err(`${id}: unknown kind ${JSON.stringify(kind)}`); }} function parseArray<T>(raw: unknown, parseItem: (item: unknown) => Result<T>): Result<T[]> { if (!Array.isArray(raw)) return err("expected an array"); const items: T[] = []; for (const item of raw) { const result = parseItem(item); if (!result.ok) return result; items.push(result.value); } return ok(items);} type ApiError = | { kind: "network"; message: string } | { kind: "http"; status: number } | { kind: "invalid"; message: string }; type RawResponse = { status: number; body: string };type Transport = (path: string) => Promise<RawResponse>; // Generic: the parser decides what T is, and the caller gets Result<T, ApiError>.async function getJson<T>(transport: Transport, path: string, parse: (raw: unknown) => Result<T>): Promise<Result<T, ApiError>> { let response: RawResponse; try { response = await transport(path); } catch (e) { return err({ kind: "network", message: e instanceof Error ? e.message : String(e) }); } if (response.status !== 200) return err({ kind: "http", status: response.status }); let raw: unknown; try { raw = JSON.parse(response.body); } catch { return err({ kind: "invalid", message: "body is not JSON" }); } const parsed = parse(raw); return parsed.ok ? parsed : err({ kind: "invalid", message: parsed.error });} function describeError(error: ApiError): string { switch (error.kind) { case "network": return `Offline? ${error.message}`; case "http": return `Server said ${error.status}`; case "invalid": return `Bad data: ${error.message}`; default: return assertNever(error); }} // A fake transport: no network, just canned responses. Tests can use the same trick.const routes = new Map<string, RawResponse>([ ["/transactions", { status: 200, body: `[{ "kind": "expense", "id": "t2", "date": "2026-10-03", "amount": 4250, "category": "food" }]` }], ["/transactions?month=09", { status: 200, body: `[{ "kind": "expense", "id": "t9", "date": "2026-09-30", "amount": -5, "category": "food" }]` }],]);const fakeTransport: Transport = async (path) => { if (path === "/offline") throw new Error("connection refused"); return routes.get(path) ?? { status: 404, body: "" };}; const listTransactions = (path: string) => getJson(fakeTransport, path, (raw) => parseArray(raw, parseTransaction)); for (const path of ["/transactions", "/transactions?month=09", "/budgets", "/offline"]) { const result = await listTransactions(path); if (result.ok) console.log(path, "->", result.value.length, "transaction(s)"); else console.log(path, "->", describeError(result.error));}
Output
Press Run (⌘ Enter) to see what happens.

Four paths, four outcomes, and not one try block in the calling code. The second path is the interesting one: the server said 200, but one amount was negative, so the whole response is rejected as bad data instead of quietly reaching your totals. parseArray<T> is a second small generic. It works for any item parser, so the same function will validate a list of budgets later.

Inside getJson, note the catch (e). Under strict, e is unknown, not any, because JavaScript lets you throw anything. So the code checks e instanceof Error before reading e.message. That flag is one of several you will see below.

Put it in order5 steps

Put the steps of one getJson call in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Stage 5: tests

Pure functions and an injected transport make testing simple. You call a function with a value and compare the result. No network, no mocks of global fetch, no setup. The block below is the whole app plus ten checks, written with a tiny check helper so it runs here. In a real project you would use the setup from Testing JavaScript and TypeScript with Vitest: each check becomes test("...", () => expect(actual).toEqual(expected)), and the files run in watch mode and in CI.

TypeScript
// The model from stage 1, written compactly.const CATEGORIES = ["food", "transport", "rent", "fun"] as const;type Category = (typeof CATEGORIES)[number];type Cents = number; interface Expense { readonly kind: "expense"; readonly id: string; readonly date: string; readonly amount: Cents; readonly category: Category }interface Refund { readonly kind: "refund"; readonly id: string; readonly date: string; readonly amount: Cents; readonly category: Category; readonly refundOf: string }interface Income { readonly kind: "income"; readonly id: string; readonly date: string; readonly amount: Cents; readonly source: string }type Transaction = Expense | Refund | Income; type Result<T, E = string> = { ok: true; value: T } | { ok: false; error: E };function ok<T>(value: T): { ok: true; value: T } { return { ok: true, value };}function err<E>(error: E): { ok: false; error: E } { return { ok: false, error };} function assertNever(value: never): never { throw new Error(`Unhandled case: ${JSON.stringify(value)}`);}function formatCents(cents: Cents): string { const sign = cents < 0 ? "-" : ""; return `${sign}$${(Math.abs(cents) / 100).toFixed(2)}`;} // Type guards: runtime checks the compiler understands.function isRecord(value: unknown): value is Record<string, unknown> { return typeof value === "object" && value !== null && !Array.isArray(value);}function isCategory(value: unknown): value is Category { return typeof value === "string" && (CATEGORIES as readonly string[]).includes(value);} function parseTransaction(raw: unknown): Result<Transaction> { if (!isRecord(raw)) return err("not an object"); const { kind, id, date, amount } = raw; if (typeof id !== "string" || id === "") return err("id must be a non-empty string"); if (typeof date !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(date)) return err(`${id}: date must be YYYY-MM-DD`); if (typeof amount !== "number" || !Number.isInteger(amount) || amount <= 0) { return err(`${id}: amount must be a positive whole number of cents`); } switch (kind) { case "expense": if (!isCategory(raw.category)) return err(`${id}: unknown category`); return ok({ kind, id, date, amount, category: raw.category }); case "refund": if (!isCategory(raw.category)) return err(`${id}: unknown category`); if (typeof raw.refundOf !== "string") return err(`${id}: refundOf must be a string`); return ok({ kind, id, date, amount, category: raw.category, refundOf: raw.refundOf }); case "income": if (typeof raw.source !== "string") return err(`${id}: source must be a string`); return ok({ kind, id, date, amount, source: raw.source }); default: return err(`${id}: unknown kind ${JSON.stringify(kind)}`); }} type CategoryTotals = Record<Category, Cents>;type NewExpense = Omit<Expense, "kind" | "id">; // what a form sends: no kind, no id yettype BudgetLine = Readonly<{ category: Category; spent: Cents; budget: Cents; over: boolean }>; // Pure: same input, same output, no side effects.function addExpense(ledger: readonly Transaction[], input: NewExpense, id: string): readonly Transaction[] { return [...ledger, { kind: "expense", id, ...input }];} function spendByCategory(ledger: readonly Transaction[]): CategoryTotals { const totals: CategoryTotals = { food: 0, transport: 0, rent: 0, fun: 0 }; for (const tx of ledger) { switch (tx.kind) { case "expense": totals[tx.category] += tx.amount; break; case "refund": totals[tx.category] -= tx.amount; break; case "income": break; // income is not spending default: assertNever(tx); } } return totals;} function budgetReport(ledger: readonly Transaction[], budgets: Readonly<CategoryTotals>): BudgetLine[] { const spent = spendByCategory(ledger); return CATEGORIES.map((category) => ({ category, spent: spent[category], budget: budgets[category], over: spent[category] > budgets[category], }));} function parseArray<T>(raw: unknown, parseItem: (item: unknown) => Result<T>): Result<T[]> { if (!Array.isArray(raw)) return err("expected an array"); const items: T[] = []; for (const item of raw) { const result = parseItem(item); if (!result.ok) return result; items.push(result.value); } return ok(items);} type ApiError = | { kind: "network"; message: string } | { kind: "http"; status: number } | { kind: "invalid"; message: string }; type RawResponse = { status: number; body: string };type Transport = (path: string) => Promise<RawResponse>; // Generic: the parser decides what T is, and the caller gets Result<T, ApiError>.async function getJson<T>(transport: Transport, path: string, parse: (raw: unknown) => Result<T>): Promise<Result<T, ApiError>> { let response: RawResponse; try { response = await transport(path); } catch (e) { return err({ kind: "network", message: e instanceof Error ? e.message : String(e) }); } if (response.status !== 200) return err({ kind: "http", status: response.status }); let raw: unknown; try { raw = JSON.parse(response.body); } catch { return err({ kind: "invalid", message: "body is not JSON" }); } const parsed = parse(raw); return parsed.ok ? parsed : err({ kind: "invalid", message: parsed.error });} function describeError(error: ApiError): string { switch (error.kind) { case "network": return `Offline? ${error.message}`; case "http": return `Server said ${error.status}`; case "invalid": return `Bad data: ${error.message}`; default: return assertNever(error); }} // ---- tests: plain assertions, the same shape as Vitest's test + expect ----let passed = 0;let failed = 0;function check(name: string, actual: unknown, expected: unknown): void { const a = JSON.stringify(actual); const b = JSON.stringify(expected); if (a === b) { passed++; } else { failed++; console.log(`FAIL ${name}\n expected ${b}\n got ${a}`); }} const lunch = { kind: "expense", id: "a", date: "2026-10-02", amount: 1200, category: "food" }; check("parses a valid expense", parseTransaction(lunch).ok, true);check("rejects a float amount", parseTransaction({ ...lunch, amount: 12.5 }), err("a: amount must be a positive whole number of cents"));check("rejects an unknown kind", parseTransaction({ ...lunch, kind: "gift" }).ok, false);check("rejects null", parseTransaction(null), err("not an object")); const ledger: readonly Transaction[] = [ { kind: "expense", id: "a", date: "2026-10-02", amount: 1200, category: "food" }, { kind: "refund", id: "b", date: "2026-10-03", amount: 200, category: "food", refundOf: "a" }, { kind: "income", id: "c", date: "2026-10-04", amount: 99999, source: "Gift" },];check("refunds reduce spending", spendByCategory(ledger).food, 1000);check("income is not spending", spendByCategory(ledger).fun, 0);check("addExpense returns a new array", addExpense(ledger, { date: "2026-10-05", amount: 1, category: "fun" }, "d").length, 4);check("ledger untouched", ledger.length, 3); const flaky: Transport = async () => ({ status: 200, body: "not json" });check("bad JSON is an invalid error", await getJson(flaky, "/x", (raw) => parseArray(raw, parseTransaction)), err({ kind: "invalid", message: "body is not JSON" }));const down: Transport = async () => ({ status: 503, body: "" });check("HTTP errors keep the status", await getJson(down, "/x", (raw) => parseArray(raw, parseTransaction)), err({ kind: "http", status: 503 })); console.log(`${passed} passed, ${failed} failed`);
Output
Press Run (⌘ Enter) to see what happens.

All ten pass. Now break something on purpose, which is the best way to trust a test. In spendByCategory, change -= to += for refunds and run the block again. One check fails with the expected and actual values side by side. Change it back.

Notice what the tests cover: the edges of the validator (a float, an unknown kind, null), the rules in the logic (refunds, income), and each failure path of the client. Those are the places bugs hide. You do not need a test that a Category is a string. The compiler already proves that.

Turning on strict

Every block in this lesson compiles with strict: true, the setting from Modules and tsconfig. strict is a group of flags. The best way to see why each one matters is the bug it catches. Here are the ones this project leans on, plus two that strict does not include:

type Tx = { id: string; amount: number; note?: string };
const ledger: Tx[] = [];
 
// noImplicitAny (in strict): parameters with no type are an error, not silently any.
function total(items) { return items.reduce((s, t) => s + t.amount, 0); }
//             ~~~~~ Parameter 'items' implicitly has an 'any' type.
 
// strictNullChecks (in strict): find can return undefined.
const found = ledger.find((t) => t.id === "t9");
console.log(found.amount);
//          ~~~~~ 'found' is possibly 'undefined'.
 
// useUnknownInCatchVariables (in strict): anything can be thrown.
try { JSON.parse("{"); } catch (e) { console.log(e.message); }
//                                              ~ 'e' is of type 'unknown'.
 
// noUncheckedIndexedAccess (not in strict): the array might be empty.
const first = ledger[0];
console.log(first.amount);
//          ~~~~~ 'first' is possibly 'undefined'.
 
// exactOptionalPropertyTypes (not in strict): "missing" and "undefined" differ.
const patch: Partial<Tx> = { note: undefined };
//    ~~~~~ Type 'undefined' is not assignable to type 'string'.

Without these flags, every line above compiles and then fails at runtime. total would accept a string. found.amount crashes when no row matches, which is exactly the case nobody tests. e.message is undefined when someone throws a string. ledger[0].amount crashes on a new user's empty ledger.

Turn on strict from day one. On an older codebase, turn the flags on one at a time and fix the errors each one shows. Add noUncheckedIndexedAccess too: it is noisy at first, but empty arrays and missing keys are some of the most common bugs in real code.

Quick check
A new user has no transactions, and ledger[0].amount crashes. Your tsconfig has strict: true. Which extra flag would have caught this at compile time?
Need a nudge? A hint rules out a wrong answer.

What to build next

The core is done. Pick one of these and build it on top:

  • Edit and delete. Write updateExpense(ledger, id, patch: Partial<NewExpense>) and removeTransaction(ledger, id). Both return a new ledger. Turn on exactOptionalPropertyTypes and see what it says about the patch.
  • A fourth kind. Add a transfer between accounts. Let assertNever show you every switch that needs a decision.
  • Monthly reports. Group the ledger by month with Map<string, Transaction[]> and print a report per month. Use Intl.NumberFormat from Dates, Time Zones and Intl instead of formatCents.
  • Swap in Zod. Replace parseTransaction with a schema, derive Transaction from it with z.infer, and run the stage 5 tests to prove nothing changed.
  • A real page. Put the core under a small UI, like the to-do app or a React app. The core does not change at all, which is the point of keeping it pure.
Key terms
domain model
The types that describe the things your app is about, such as Transaction, Category and Cents, independent of any UI or server.
discriminated union
A union of object types that share a literal field, like kind, so a switch on that field narrows to one member.
exhaustive check
Passing the leftover value to a function that accepts never, so a missing case becomes a compile error.
type guard
A function returning value is T that checks a value at runtime and narrows its type for the compiler.
Result type
A union like { ok: true; value } | { ok: false; error } that makes failure part of a function's return type.
transport
The function that actually sends a request. Passing it in lets tests swap the network for canned responses.
strict mode
The strict tsconfig flag, a group of checks such as strictNullChecks and noImplicitAny that catch common runtime bugs.

That is a typed core you could ship. The wrap-up next pulls the whole course together around one more realistic feature, from the form to the network and back.