Skip to content
Tutorials Center
My learning

Topics

Lesson 83 of 96 ยท Projects

Project: Task Board

Build a Kanban-style task board in TypeScript - a typed task model, columns with WIP limits, filters, a storage adapter with validation, and undo/redo.

A task board (the Kanban style of Trello, Jira or GitHub Projects) is a great TypeScript project because it has a little of everything real apps have: a data model with rules, user actions that change it, views that filter and sort it, data that must survive a page reload, and an Undo button that people expect to just work.

In this project you'll build the core of such a board, independent of any UI framework. You'll define a typed task model where invalid states don't compile, change it only through commands (a discriminated union), add filters and sorting described as plain data, save the board through a storage adapter interface with runtime validation, and finish with a generic undo/redo history. Each stage is a complete program you can run. The browser-only localStorage adapter appears as read-only code, because our editor runs on Node.js without browser storage.

The plan

Stage What you build Main TypeScript ideas
1 Task model, columns and commands as const arrays, branded IDs, Readonly, Record, discriminated unions, Result
2 Filters and sorting Optional filter fields, generic predicates, mapped comparator tables
3 Persistence An adapter interface, versioned formats, unknown validation, type predicates
4 Undo and redo A generic History<T>, immutable updates, getters

Stage 1: the task model

Start with the vocabulary. The columns come from one as const array, so the Status type and the column order at runtime can never disagree (see Literal Types and as const). Task IDs get a brand, so a random string can't be passed where a real ID is expected (the same trick as in Type-Level Programming).

The board stores tasks by ID plus an ordered list of IDs per column. Ordering is a property of the column, not of the task, so moving a card never has to renumber other tasks. Every field is readonly, which makes accidental mutation a compile error and keeps undo (stage 4) simple: each change produces a new board, and old boards stay valid.

All changes go through one function, apply(board, command). A Command is a discriminated union: move must say where to, edit may change only the title, priority or tags (Partial<Pick<Task, โ€ฆ>>, see utility types), and nothing can change a task's ID. Because some commands can fail (moving a missing task, or into a full column), apply returns a Result instead of throwing, as in Error Handling:

TypeScript Stage 1: the task model and board commands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
rejected move: "doing" is full (limit 2)
rejected remove: no task t9
TODO  | Write API docs (t3)
DOING | Fix CSS bug (t4) | Login page (t2)
DONE  | !Design schema (t1)

The "doing" column has a work-in-progress limit of 2, a common Kanban rule. The third move is rejected while two tasks are in progress; once "Design schema" moves to done, "Fix CSS bug" fits and goes to the top of the column because of index: 0. Removing a task that doesn't exist is reported, not ignored.

Notice how switch (command.type) narrows: inside case 'move', command.to and command.index exist; inside case 'edit', command.changes does. And because every case returns, TypeScript knows apply always produces a Result<Board>. Add a fifth command and forget its case, and the function no longer compiles.

The types also reject commands that make no sense. This program shows three of them:

TypeScript Commands the model rejects (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Nothing runs; the compiler reports three errors:

TEXT
main.ts(12,21): error TS2322: Type 'string' is not assignable to type 'TaskId'.
  Type 'string' is not assignable to type '{ readonly __brand: "TaskId"; }'.
main.ts(13,41): error TS2322: Type '"blocked"' is not assignable to type 'Status'.
main.ts(14,43): error TS2353: Object literal may only specify known properties, and 'to' does not exist in type '{ type: "remove"; id: TaskId; }'.

A plain string isn't a TaskId, 'blocked' isn't a column, and a remove command can't carry a destination. In a real app, IDs come from newTaskId() or from validated stored data, which are the only places that use as TaskId.

Stage 2: filters and sorting

Users filter boards constantly: "only my frontend tasks", "what's overdue?", "high priority, not done yet". A good design keeps the filter as plain data, an object with optional fields, and turns it into a function separately. Data can be saved, put into a URL query string or compared; functions can't.

toPredicate builds a list of small checks, one per field that's set, and combines them with a generic all<T>() helper. Each check is a Predicate<Task>, a (task) => boolean function, so new filters are easy to add. Sorting uses a mapped type over the allowed sort keys: the comparators table must have exactly one comparator per SortKey, so adding 'status' to the union without a comparator is a compile error.

TypeScript Stage 2: typed filters and sorting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
frontend, by priority: [
  't4 Fix CSS bug [high, due 2026-10-17]',
  't2 Login page [normal, due 2026-10-20]'
]
overdue: [ 't4 Fix CSS bug [high, due 2026-10-17]' ]
next 7 days: [
  't2 Login page [normal, due 2026-10-20]',
  't5 Rate limiting [high, due 2026-10-24]'
]
open high-priority: [
  't4 Fix CSS bug [high, due 2026-10-17]',
  't5 Rate limiting [high, due 2026-10-24]'
]
text "page": [ 't2 Login page [normal, due 2026-10-20]' ]

"Design schema" has an older due date but isn't overdue, because it's done. The today parameter has a default, which makes the function easy to test: pass a fixed date and the output never changes, instead of depending on the clock. A few typing details:

  • statuses?: readonly Status[] accepts both mutable arrays and as const tuples, and statuses.includes(t.status) type-checks because the element type matches.
  • Destructuring const { text, statuses, โ€ฆ } = filter before building the closures matters: TypeScript keeps the narrowing from if (statuses) inside the arrow function because statuses is a const that can't change later.
  • priorityRank: Record<Priority, number> ranks the priorities. Using Record forces every priority to have a rank.

Stage 3: saving the board

A board that disappears on reload isn't much use. But where should it be stored? In the browser that's localStorage (or IndexedDB); on a server it's a database; in tests it's memory. The app shouldn't care, so it depends on an interface (a "port") and each storage gets a small adapter class that implements it:

TypeScript
interface BoardStorage {
  load(): Promise<Board | null>;
  save(board: Board): Promise<void>;
}

The methods return promises even though localStorage is synchronous: an IndexedDB or HTTP adapter will be asynchronous, and the interface should fit all of them.

Loading is where the real typing work is. Stored text can be anything: a value from an older app version, data edited by hand, or a truncated write. JSON.parse returns any, so the code below immediately treats the result as unknown and checks it with type guards before it becomes a Board. The stored format carries a version number, so a future version 2 can migrate old data instead of misreading it:

TypeScript Stage 3: a storage adapter with validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
nothing valid saved: starting empty
stored text: {"version":1,"board":{"tasks":[{"id":"t1","title":"Design schema","status":"doing"}]}}
loaded 1 task(s)
[ { id: 't1', title: 'Design schema', status: 'doing' } ]
nothing valid saved: starting empty
nothing valid saved: starting empty
nothing valid saved: starting empty

The three broken inputs (invalid JSON, an unknown version and a task with the status 'blocked') are all rejected, so the app starts with an empty board instead of crashing later on a value its types said was impossible. In a real app you'd keep a copy of the unreadable data and tell the user, rather than silently dropping it. satisfies StoredBoardV1 in serialize checks the written shape without changing its type, so the save and load formats can't drift apart (see The satisfies Operator).

Here is the browser adapter. It implements the same interface, so startApp(new LocalStorageBoardStorage()) works unchanged. It needs the DOM library, so it's read-only here:

TypeScript
class LocalStorageBoardStorage implements BoardStorage {
  constructor(private readonly key = 'task-board') {}

  async load(): Promise<Board | null> {
    try {
      const text = localStorage.getItem(this.key); // string | null
      return text === null ? null : parseStoredBoard(text);
    } catch {
      return null; // storage blocked: private mode, sandboxed iframe, disabled cookies
    }
  }

  async save(board: Board): Promise<void> {
    try {
      localStorage.setItem(this.key, serialize(board));
    } catch (error) {
      if (error instanceof DOMException && error.name === 'QuotaExceededError') {
        throw new Error('Browser storage is full; the board was not saved');
      }
      throw error;
    }
  }

  /** Call `listener` when another tab changes the board. Returns an unsubscribe function. */
  subscribe(listener: (board: Board) => void): () => void {
    const onStorage = (event: StorageEvent): void => {
      if (event.key !== this.key || event.newValue === null) return;
      const board = parseStoredBoard(event.newValue);
      if (board) listener(board);
    };
    window.addEventListener('storage', onStorage);
    return () => window.removeEventListener('storage', onStorage);
  }
}

Three browser realities show up in the types and the code: getItem returns string | null, localStorage itself can throw when storage is blocked, and writes can fail when the quota is full. The extra subscribe method uses the storage event, which fires in other tabs when one tab writes, so two open tabs stay in sync. It isn't part of BoardStorage, because not every storage can notify; a separate optional interface would be the clean way to add it. The web storage lesson covers localStorage itself in detail.

Stage 4: undo and redo

Because every command returns a new board and never changes the old one, undo is almost free: keep the previous boards in a list. The classic structure has three parts: past (older states, newest last), present, and future (states you've undone, ready to redo). A new command clears the future, as in every text editor.

The history is generic, History<T>, so it works for the board or for anything else immutable. createHistory returns an object with getters (state, canUndo, canRedo) that a UI can use to enable or disable its buttons, and a limit keeps memory bounded:

TypeScript Stage 4: undo and redo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
start          (empty)  [undo off, redo off]
3 commands     Schema:done, Login:todo  [undo on, redo off]
removed Login  Schema:done  [undo on, redo off]
undo           Schema:done, Login:todo  [undo on, redo on]
undo again     Schema:todo, Login:todo  [undo on, redo on]
redo           Schema:done, Login:todo  [undo on, redo on]
new command    Schema:done, Login:doing  [undo on, redo off]
redo (no-op)   Schema:done, Login:doing  [undo on, redo off]

The first undo brings "Login" back, the second moves "Schema" back to todo, and redo re-applies the move. Then a new command (moving Login) clears the future, so the final redo does nothing. A few details:

  • Object.is(next, history.present) skips updates that return the very same state object (a reducer that returns the board unchanged when a command is rejected, for example), so they don't create empty undo steps.
  • history.past.at(-1) returns T | undefined, so the compiler makes undo() handle an empty history.
  • Storing whole boards sounds expensive, but immutable updates share structure: unchanged tasks are the same objects in every snapshot, so each step costs only the changed parts.

Putting it all together in the app is a few lines: run each command through apply, push successful results into the history, and save history.state with the storage adapter after each change (debounced, so fast typing doesn't write on every key).

Ideas for extending the board

  • Add a due date to the stage 1 model, a 'setDue' command, and reuse the stage 2 filters on the real Board type.
  • Support swimlanes (rows per assignee) by changing columns to Record<Status, Record<AssigneeId, TaskId[]>>, and let the compiler show every place that needs updating.
  • Write a version 2 storage format (for example adding createdAt) and a migrate(v1): V2 function, keeping parseStoredBoard able to read both.
  • Make the history store commands instead of whole boards, and undo by replaying all but the last one from the initial state.
  • Connect it to a UI: the DOM widgets project shows the drag-and-drop and keyboard pieces, and TypeScript with React shows how a reducer like apply plugs into useReducer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is the task ID typed string & { readonly __brand: 'TaskId' } instead of string?

    The brand exists only in the type system. Plain strings aren't assignable to TaskId, so IDs must come from the few places that create or validate them.
  2. 2. edit commands carry changes: Partial<Pick<Task, 'title' | 'priority' | 'tags'>>. Which of these compiles?

    Pick limits the keys to title, priority and tags, and Partial makes each optional. id and status can't be edited this way, and changes itself is required.
  3. 3. Why does parseStoredBoard treat the parsed JSON as unknown and check it, instead of using JSON.parse(text) as Board?

    An as assertion only tells the compiler to trust you. Type guards check the actual value, so invalid data is rejected at the boundary instead of causing errors later.
  4. 4. In the history, what happens to the future list when you run a new command after undoing?

    A new command starts a new branch of history. Like text editors, the board discards the undone states.
  5. 5. The comparators table is typed { [K in SortKey]: (a: Task, b: Task) => number }. You add 'status' to SortKey. What happens?

    The mapped type requires one property per key, so a missing comparator is a compile error (TS2741), not a runtime surprise.

Summary

  • Derive types from runtime constants (STATUSES โ†’ Status), brand IDs, and make the model readonly, so invalid boards and accidental mutations don't compile.
  • Change state only through a Command union and one apply function; return Result for expected failures such as WIP limits and missing tasks.
  • Keep filters as plain data, turn them into composable Predicate<T> functions, and use mapped types so every sort key has a comparator.
  • Depend on a BoardStorage interface; adapters for memory and localStorage implement it. Treat stored data as unknown, version it and validate it with type guards.
  • Immutable updates make undo/redo simple: a generic History<T> with past, present and future, cleared future on new commands, and a size limit.

Next: TypeScript Cheat Sheet