← Back to course: TypeScript from scratch

Final project: typed task manager

Video coming soon

The time has come to put everything you have learned together in a complete project: a command-line task manager written in strict TypeScript, which saves its data in a JSON file. It is a small project, but it uses almost every topic in the course: object types, literal unions, typed functions, generics, classes, modules, utility types, discriminated unions and validation of external data. Work at your own pace, over several sessions if needed, and compile often: letting the compiler guide you is part of the learning.

Brief and requirements

Build an application called taskr used from the terminal with commands such as add, list, done, remove and clear-done. Each task has an id, a title, a priority, a completed state and a creation date. Data is saved in tasks.json and is read and validated at startup. If the file is corrupt or does not exist, the application must react with a clear message and not with an unexpected crash. The technical requirements are the following.

  • tsconfig with strict, noUncheckedIndexedAccess, noImplicitReturns and module NodeNext; package.json with type module and build, check and dev scripts.
  • Separate files: models.ts (types), validate.ts (validation), storage.ts (reading and writing), manager.ts (TaskManager class) and index.ts (command interface).
  • Priority as a union of literals: 'low' | 'medium' | 'high'. Commands as a discriminated union.
  • TaskManager with typed methods add, complete, remove, list(filter) and clearDone; none may use any.
  • File data is read as unknown and validated with type guards before use.
  • A generic type Result<T> for operations that can fail, instead of throwing exceptions in the logic.
  • npx tsc --noEmit must finish with no errors.

Step 1: the models

Start with the types: they are the design of your program. Think first about the data and the possible states; then the logic almost writes itself. Here is a starting point for models.ts, with the key pieces: the task, the priority, the filter, the result and the commands as a discriminated union.

typescript
// src/models.ts
export type Priority = 'low' | 'medium' | 'high';

export interface Task {
  readonly id: number;
  title: string;
  priority: Priority;
  done: boolean;
  readonly createdAt: string; // ISO date
}

export type NewTask = Pick<Task, 'title' | 'priority'>;
export type TaskFilter = 'all' | 'pending' | 'done';

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

export type Command =
  | { name: 'add'; title: string; priority: Priority }
  | { name: 'list'; filter: TaskFilter }
  | { name: 'done'; id: number }
  | { name: 'remove'; id: number }
  | { name: 'clear-done' };

export const PRIORITIES: readonly Priority[] = ['low', 'medium', 'high'];

Step 2: validation and the class

In validate.ts write isPriority(value: unknown) and isTask(value: unknown), and a function parseTasks(json: string): Result<Task[]> that parses the text, checks it is an array and that every element is a valid task. In manager.ts create the TaskManager class: it stores the tasks in a private property, computes the next id from the largest existing one and returns Result<Task> in add, complete and remove. This is a skeleton with the main methods; complete the rest yourself.

typescript
// src/manager.ts
import type { NewTask, Result, Task, TaskFilter } from './models.js';

export class TaskManager {
  private tasks: Task[];

  constructor(initial: Task[] = []) {
    this.tasks = [...initial];
  }

  private nextId(): number {
    return this.tasks.reduce((max, t) => Math.max(max, t.id), 0) + 1;
  }

  add(input: NewTask): Result<Task> {
    const title = input.title.trim();
    if (title === '') {
      return { ok: false, error: 'Title cannot be empty' };
    }
    const task: Task = {
      id: this.nextId(),
      title,
      priority: input.priority,
      done: false,
      createdAt: new Date().toISOString(),
    };
    this.tasks.push(task);
    return { ok: true, value: task };
  }

  complete(id: number): Result<Task> {
    const task = this.tasks.find((t) => t.id === id);
    if (!task) {
      return { ok: false, error: 'Task ' + id + ' not found' };
    }
    task.done = true;
    return { ok: true, value: task };
  }

  list(filter: TaskFilter = 'all'): readonly Task[] {
    if (filter === 'all') {
      return this.tasks;
    }
    return this.tasks.filter((t) => (filter === 'done' ? t.done : !t.done));
  }

  toArray(): Task[] {
    return [...this.tasks];
  }
}

const demo = new TaskManager();
console.log(demo.add({ title: 'Finish the course', priority: 'high' }));

Step 3: storage and commands

In storage.ts write loadTasks(path): Result<Task[]> and saveTasks(path, tasks): void using node:fs; if the file does not exist, return an empty list. In index.ts, turn process.argv into a Command through a function parseCommand(args: string[]): Result<Command>, and run the command with an exhaustive switch on command.name using assertNever. At the end, save the changes. To test, run npx tsx src/index.ts add 'Study generics' high, then list and done 1.

Test what you learned

Question 1 of 6

Why is response.json() a risk to type safety?

✎ My notes

Saved only in this browser. Sign in to keep it in your account.0/5000 characters

← Previous