Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 96 ยท Projects

Project: Typed To-Do CLI

Build a command-line to-do app in TypeScript - parse commands into a discriminated union, keep a typed store, format a table and add undo with an immutable reducer.

Time to put the pieces together. In this project you'll build a small command-line to-do manager. It reads commands such as add Buy milk !high #home, done 1 and list open, one per line, and prints the results. It's a classic first project because it's small enough to finish, yet it touches almost every everyday TypeScript skill: literal types, discriminated unions, narrowing, classes, readonly data, utility types and exhaustive checks.

You'll build it in four stages, and every stage is a complete program you can run. The commands come from standard input, which is preset in each editor's Input box, so pressing Run just works. Change the input lines to try your own commands.

The plan

Stage What you build Main TypeScript ideas
1 A parser that turns text lines into typed commands Literal unions, as const, discriminated unions, a Result-style return type
2 A store and a command executor Classes with #private fields, exhaustive switch with never
3 New commands and a formatted table Growing a union safely, Record<Priority, number>, string formatting
4 Undo, using an immutable reducer readonly everywhere, Exclude<>, pure functions

The commands the finished app understands:

TEXT
add <title words> [!low|!normal|!high] [#tag ...]   add a to-do
done <id>                                          mark a to-do as done
remove <id>                                        delete a to-do
rename <id> <new title>                            change a title        (stage 3)
clear                                              delete all done to-dos (stage 3)
list [all|open|done]                               show to-dos
undo                                               undo the last change  (stage 4)
help                                               show this list

Stage 1: parsing commands into a union

The first job is turning untrusted text into data the rest of the program can trust. Each command becomes one member of a discriminated union (Discriminated Unions), tagged by kind. Once a line has been parsed, no other code ever looks at raw strings again.

Parsing can fail, so parseLine doesn't throw. It returns either { ok: true, command } or { ok: false, error }. Callers must check ok before they can reach command, so a failed parse can't be forgotten.

TypeScript Stage 1: a typed command parser

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.

The output shows five valid commands and three errors (remove x, !urgent and fly away), and the blank line is skipped. A few details worth a closer look:

  • One source of truth for the literals. PRIORITIES is an as const array, and Priority is derived from it with (typeof PRIORITIES)[number] (keyof, typeof and Indexed Access Types). The runtime list used for validation and the compile-time type can never drift apart.
  • Type guards narrow strings. isPriority(level) returns value is Priority, so after the check priority = level compiles: TypeScript knows level is one of the three literals.
  • Narrowing inside switch. In case 'done': case 'remove': TypeScript narrows name from string to 'done' | 'remove'. That's why { kind: name, id } is accepted as a Command: either value of kind produces a valid union member.
  • Defaults in destructuring. const [name = '', ...rest] gives name the type string even when the line is empty.

Try writing return ok({ kind: 'add', title: words.join(' '), tags }); without priority. The compiler rejects it, because every add command must have a priority. The union describes exactly which fields each command needs.

Stage 2: a store and an exhaustive executor

Now the commands need to do something. A TodoStore class owns the list of to-dos. Its fields are JavaScript #private fields (Access Modifiers and Private Fields), so nothing outside the class can push into the array or reset the id counter. Its list method returns readonly Todo[], so callers can read the list but not change it.

The execute function switches on command.kind. In the default branch, command has been narrowed to never: every possible kind has been handled. Passing it to assertNever(value: never) turns a forgotten case into a compile error, as you'll see in stage 3.

TypeScript Stage 2: storing and executing 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.

The parser is the same as in stage 1, just written more compactly. Look at how little checking execute needs: inside case 'done', command.id is known to be a number, and inside case 'add', command.title and command.tags exist. There isn't a single ?., ! or as in the executor.

Two design decisions are worth noticing:

  • complete and remove return Todo | undefined instead of throwing. A missing id is a normal situation for a CLI, and the return type forces execute to handle it (todo ? ... : ...). Forgetting that check would be error TS18048, 'todo' is possibly 'undefined'.
  • Todo marks every field readonly except done, the only one that ever changes. That documents the data model in the type itself.

Stage 3: growing the union safely

Real programs grow. Let's add two commands: rename <id> <title> and clear (delete every finished to-do). The first step is adding them to the Command union. Here's the payoff of assertNever: the moment the union gains a member that execute doesn't handle, the program stops compiling. This tiny program shows the effect on its own:

TypeScript A forgotten case (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 main.ts(14,26): error TS2345: Argument of type '{ kind: "rename"; id: number; title: string; }' is not assignable to parameter of type 'never'. The message even tells you which command you forgot. In a large program with many switch statements over the same union, every one of them lights up, so no handler is missed.

With both commands handled, this stage also replaces the plain list with a real table: open to-dos first, then by priority (high to low), then by id. The priority order lives in a Record<Priority, number>, which must contain exactly one entry for each priority, so adding an 'urgent' level later would be a compile error here until you rank it.

TypeScript Stage 3: rename, clear and a formatted table

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.

The table lists the two high-priority open tasks first, then the normal and low ones, and the finished task last. Notice the shared case 'done': case 'rename': branch: after the if (command.kind === 'done') check returns, TypeScript narrows command to the rename member, so command.title is available in the last three lines without any extra check.

title lost its readonly modifier in this stage because rename changes it. That's a small sign the design is getting harder to reason about: more and more of a Todo can change from anywhere that holds a reference to it. Stage 4 fixes that.

Stage 4: undo with an immutable reducer

Undo is hard when objects are changed in place, because the old values are gone. It becomes trivial when you never change anything: each command produces a new state, and undo simply goes back to the previous one. This is the reducer pattern, made popular by Redux and React's useReducer.

The state type is readonly all the way down, so an accidental mutation such as state.todos.push(...) or todo.done = true is a compile error. The reducer only accepts commands that change data. Exclude (Built-in Utility Types) derives that type from Command, so the list stays correct as commands are added:

TypeScript
type ChangeCommand = Exclude<Command, { kind: 'list' | 'help' | 'undo' }>;
// = add | done | remove | rename | clear
TypeScript Stage 4: the complete CLI with undo

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.

Follow the output: two undo commands bring back the removed "Water the plants" task and then reopen "Buy milk". done 9 fails, and because the reducer returned the same state object, nothing was pushed onto the history, so the next undo steps back over a real change, not a failed command. The fourth undo finds the history empty, and the final list shows nothing because every change has been undone.

Several pieces of TypeScript make this design safe:

  • Deep readonly. State, Todo and their arrays are read-only, so the only way to "change" anything is to build a new object with spread syntax. Try adding state.todos.push(...) inside reduce: it's a compile error. See Readonly and Immutability.
  • Narrowing by elimination. In run, the default branch is reached only after list, help and undo have been handled, so TypeScript narrows command to exactly ChangeCommand and the call reduce(state, command) type-checks with no assertion.
  • Two exhaustive switches. reduce covers every change command (with assertNever), and run covers the rest. Add a new command to Command and the compiler tells you which of the two must handle it.
  • Sharing data is safe. Undo keeps old states in history, and new states share unchanged Todo objects with old ones. With mutable objects that sharing would corrupt the history; with readonly types it can't happen.

On a real computer you'd run this file with node todo.ts < commands.txt, or type commands interactively by reading lines with node:readline (see TypeScript with Node.js). Saving the state between runs is one line too: writeFileSync('todos.json', JSON.stringify(state)). Loading it back should go through a type guard, because a JSON file is outside data.

Ideas for extending the CLI

  • Add edit <id> !high to change a priority. Start by adding it to Command and let the compiler errors guide you.
  • Add list #home to filter by tag. Model the filter as a union: { by: 'status'; status: ListFilter } | { by: 'tag'; tag: string }.
  • Add redo, using a second stack that undo pushes onto and every change clears.
  • Add due dates (due:2026-12-01), stored as strings in ISO format and validated by a regular expression.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In case 'done': case 'remove': with name: string, what is the type of name inside the case?

    Comparing a string with literals in switch cases narrows it to the matching literals, so name is 'done' | 'remove', which is why { kind: name, id } is a valid Command.
  2. 2. You add { kind: 'edit'; id: number } to the Command union but don't handle it. Where does the compiler complain?

    The default branch no longer narrows command to never; it is the edit member. Passing it to a never parameter is error TS2345, which points at the forgotten case.
  3. 3. What does Exclude<Command, { kind: 'list' | 'help' | 'undo' }> produce?

    Exclude removes every union member assignable to the second type. The list, help and undo members are assignable to it, so the change commands remain.
  4. 4. In stage 4, why does a failed command such as done 9 not create an undo step?

    updateTodo returns { state, message } with the original state when the id is missing, so outcome.state === state and nothing is pushed onto history.
  5. 5. Why is PRIORITY_RANK typed as Record<Priority, number> instead of Record<string, number>?

    With Priority as the key type, a missing or misspelled priority is a compile error, and PRIORITY_RANK[t.priority] is always a number.

Summary

  • Parse untrusted text once into a discriminated union; the rest of the program works with typed commands only.
  • Derive literal unions from as const arrays with (typeof ARRAY)[number] so runtime validation and types share one source of truth.
  • Return a { ok: true } | { ok: false } result from functions that can fail in normal use, instead of throwing.
  • An exhaustive switch with assertNever turns every new union member into a list of compile errors at exactly the places that must handle it.
  • Record<Priority, number> forces a complete lookup table; readonly arrays and toSorted keep data unchanged.
  • An immutable state plus a pure reducer makes undo a simple stack of old states; Exclude derives the reducer's command type from the full union.

Next: Project: Inventory with Generics