Tutorials / TypeScript: Beginner to Advanced / Final project: a type-safe task manager

Final project: a type-safe task manager

25 min read typescript
Course contents (16 lessons)
  1. Getting started
  2. Why TypeScript? What it is and what it is not
  3. Setting up TypeScript: tsc and tsconfig.json
  4. Core types
  5. Basic types: primitives, arrays, tuples, any and unknown
  6. Typing functions: parameters, returns, optionals and overloads
  7. Objects, interfaces and type aliases
  8. Unions, literals and enums
  9. Union types and type narrowing
  10. Literal types, enums and as const
  11. Classes and generics
  12. Classes in TypeScript
  13. Generics: writing reusable typed code
  14. Built-in utility types: Partial, Pick, Omit, Record and more
  15. Advanced types
  16. Mapped and conditional types
  17. Modules, type imports and declaration files
  18. TypeScript in real projects
  19. Typing async code and API responses
  20. Strict mode and compiler flags that matter
  21. Migrating a JavaScript project to TypeScript
  22. Final project: a type-safe task manager

What we are building

A small task manager library with a command interface. It does not need a database or a browser, since the goal is to practise the type system on realistic code. It uses almost everything from the course:

  • Interfaces and literal types to describe tasks.
  • A generic Repository<T> that works for any item with an id.
  • A discriminated union for commands, with an exhaustive switch.
  • A Result type for expected failures.
  • Runtime validation of untyped input, using a type guard.
  • Async code with typed promises.
  • Utility types for update inputs.

Everything is in one file so you can run it. In a real project you would split it into modules, as in the modules lesson.

The complete code

// ---------- Types ----------
type Priority = "low" | "medium" | "high";

interface Task {
  id: number;
  title: string;
  done: boolean;
  priority: Priority;
}

type NewTask = Omit<Task, "id" | "done">;
type TaskChanges = Partial<Omit<Task, "id">>;

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

// ---------- A generic repository ----------
interface HasId {
  id: number;
}

class Repository<T extends HasId> {
  private items = new Map<number, T>();

  add(item: T): void {
    this.items.set(item.id, item);
  }

  get(id: number): T | undefined {
    return this.items.get(id);
  }

  update(id: number, changes: Partial<Omit<T, "id">>): Result<T> {
    const existing = this.items.get(id);
    if (!existing) {
      return { ok: false, error: `Item ${id} not found` };
    }
    const updated: T = { ...existing, ...changes };
    this.items.set(id, updated);
    return { ok: true, value: updated };
  }

  remove(id: number): boolean {
    return this.items.delete(id);
  }

  all(): T[] {
    return [...this.items.values()];
  }
}

// ---------- Validation of untyped data ----------
const PRIORITIES: readonly Priority[] = ["low", "medium", "high"];

function isPriority(value: unknown): value is Priority {
  return typeof value === "string" && (PRIORITIES as readonly string[]).includes(value);
}

function isNewTask(value: unknown): value is NewTask {
  if (typeof value !== "object" || value === null) return false;
  const record = value as Record<string, unknown>;
  return typeof record.title === "string" && record.title.trim() !== "" && isPriority(record.priority);
}

function parseNewTasks(json: string): Result<NewTask[]> {
  let data: unknown;
  try {
    data = JSON.parse(json);
  } catch {
    return { ok: false, error: "Input is not valid JSON" };
  }
  if (!Array.isArray(data) || !data.every(isNewTask)) {
    return { ok: false, error: "Input must be an array of { title, priority }" };
  }
  return { ok: true, value: data };
}

// ---------- Commands (discriminated union) ----------
type Command =
  | { type: "add"; task: NewTask }
  | { type: "complete"; id: number }
  | { type: "retitle"; id: number; title: string }
  | { type: "remove"; id: number };

function assertNever(value: never): never {
  throw new Error(`Unhandled command: ${JSON.stringify(value)}`);
}

class TaskManager {
  private repo = new Repository<Task>();
  private nextId = 1;

  run(command: Command): Result<string> {
    switch (command.type) {
      case "add": {
        const task: Task = { id: this.nextId++, done: false, ...command.task };
        this.repo.add(task);
        return { ok: true, value: `Added #${task.id}: ${task.title}` };
      }
      case "complete": {
        const changes: TaskChanges = { done: true };
        const result = this.repo.update(command.id, changes);
        return result.ok
          ? { ok: true, value: `Completed #${command.id}` }
          : result;
      }
      case "retitle": {
        const result = this.repo.update(command.id, { title: command.title });
        return result.ok
          ? { ok: true, value: `Renamed #${command.id} to "${command.title}"` }
          : result;
      }
      case "remove":
        return this.repo.remove(command.id)
          ? { ok: true, value: `Removed #${command.id}` }
          : { ok: false, error: `Item ${command.id} not found` };
      default:
        return assertNever(command);
    }
  }

  summary(): Record<Priority, number> {
    const counts: Record<Priority, number> = { low: 0, medium: 0, high: 0 };
    for (const task of this.repo.all()) {
      if (!task.done) counts[task.priority]++;
    }
    return counts;
  }

  list(): string[] {
    return this.repo.all().map(t => `${t.done ? "[x]" : "[ ]"} #${t.id} ${t.title} (${t.priority})`);
  }
}

// ---------- Async source of tasks ----------
function wait(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function loadTasksFromServer(): Promise<string> {
  await wait(20);   // stands in for a fetch call
  return JSON.stringify([
    { title: "Write the lesson", priority: "high" },
    { title: "Review the code", priority: "medium" },
    { title: "Water the plants", priority: "low" },
  ]);
}

// ---------- Run it ----------
async function main(): Promise<void> {
  const manager = new TaskManager();

  const parsed = parseNewTasks(await loadTasksFromServer());
  if (!parsed.ok) {
    console.log("Could not load tasks:", parsed.error);
    return;
  }
  for (const task of parsed.value) {
    console.log(manager.run({ type: "add", task }));
  }

  console.log(manager.run({ type: "complete", id: 1 }));
  console.log(manager.run({ type: "retitle", id: 2, title: "Review the pull request" }));
  console.log(manager.run({ type: "remove", id: 99 }));

  console.log(manager.list().join("\n"));
  console.log("Open tasks by priority:", manager.summary());

  console.log(parseNewTasks("not json"));
  console.log(parseNewTasks('[{"title": "x", "priority": "urgent"}]'));
}

main();

Save it as tasks.ts and check it with npx tsc --noEmit --strict tasks.ts. If your Node version can run TypeScript, use node tasks.ts, or compile and run the output.

How the types help

Literal union and derived types. Priority is a union, so "urgent" is rejected by the compiler. NewTask and TaskChanges are made from Task with Omit and Partial. If you add a field to Task, both follow automatically.

The generic repository. Repository<T extends HasId> works for tasks, users or anything else with a numeric id. The update method accepts Partial<Omit<T, "id">>, so it is impossible to change an id by accident.

Validation at the edge. Data from the "server" starts as unknown. isNewTask and parseNewTasks check it for real, and only then does it become NewTask[]. Inside the program, no one needs to doubt a task.

Result instead of exceptions. run returns Result<string>, so the caller must check ok before reading value or error. Notice how return result in the complete branch is accepted when result.ok is false: the compiler has narrowed it to the failure shape, which matches Result<string> too.

Exhaustive commands. The default branch calls assertNever. Add a fifth command type to the union and the compiler shows an error here until you handle it.

Common mistakes

  • Trusting data from a network call because it has an interface. We validated it first.
  • **Using any in the repository to make update compile.** The Partial<Omit<T, "id">> signature is the proper answer.
  • Mutating objects in place. We create a new object with spread, so older references do not change unexpectedly.
  • **Forgetting the default case in the switch.** Without it, new commands are ignored silently.
  • **Casting parsed JSON with as NewTask[].** It would skip all the checks.

Try it yourself

  1. Add a command { type: "setPriority"; id: number; priority: Priority }. Let the compiler tell you what is missing, then implement it.
  2. Add a dueDate field to Task as an optional string, update validation, and show overdue tasks in list().
  3. Make Repository<T> expose a find(predicate: (item: T) => boolean): T[] method and use it to list only high priority tasks.
  4. Split the file into modules: types.ts, repository.ts, validation.ts and main.ts. Use import type where appropriate, and run tsc --noEmit.
  5. Replace the hand-written guards with a validation library, and compare the amount of code.
typescript
// ---------- Types ----------
type Priority = "low" | "medium" | "high";

interface Task {
  id: number;
  title: string;
  done: boolean;
  priority: Priority;
}

type NewTask = Omit<Task, "id" | "done">;
type TaskChanges = Partial<Omit<Task, "id">>;

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

// ---------- A generic repository ----------
interface HasId {
  id: number;
}

class Repository<T extends HasId> {
  private items = new Map<number, T>();

  add(item: T): void {
    this.items.set(item.id, item);
  }

  get(id: number): T | undefined {
    return this.items.get(id);
  }

  update(id: number, changes: Partial<Omit<T, "id">>): Result<T> {
    const existing = this.items.get(id);
    if (!existing) {
      return { ok: false, error: `Item ${id} not found` };
    }
    const updated: T = { ...existing, ...changes };
    this.items.set(id, updated);
    return { ok: true, value: updated };
  }

  remove(id: number): boolean {
    return this.items.delete(id);
  }

  all(): T[] {
    return [...this.items.values()];
  }
}

// ---------- Validation of untyped data ----------
const PRIORITIES: readonly Priority[] = ["low", "medium", "high"];

function isPriority(value: unknown): value is Priority {
  return typeof value === "string" && (PRIORITIES as readonly string[]).includes(value);
}

function isNewTask(value: unknown): value is NewTask {
  if (typeof value !== "object" || value === null) return false;
  const record = value as Record<string, unknown>;
  return typeof record.title === "string" && record.title.trim() !== "" && isPriority(record.priority);
}

function parseNewTasks(json: string): Result<NewTask[]> {
  let data: unknown;
  try {
    data = JSON.parse(json);
  } catch {
    return { ok: false, error: "Input is not valid JSON" };
  }
  if (!Array.isArray(data) || !data.every(isNewTask)) {
    return { ok: false, error: "Input must be an array of { title, priority }" };
  }
  return { ok: true, value: data };
}

// ---------- Commands (discriminated union) ----------
type Command =
  | { type: "add"; task: NewTask }
  | { type: "complete"; id: number }
  | { type: "retitle"; id: number; title: string }
  | { type: "remove"; id: number };

function assertNever(value: never): never {
  throw new Error(`Unhandled command: ${JSON.stringify(value)}`);
}

class TaskManager {
  private repo = new Repository<Task>();
  private nextId = 1;

  run(command: Command): Result<string> {
    switch (command.type) {
      case "add": {
        const task: Task = { id: this.nextId++, done: false, ...command.task };
        this.repo.add(task);
        return { ok: true, value: `Added #${task.id}: ${task.title}` };
      }
      case "complete": {
        const changes: TaskChanges = { done: true };
        const result = this.repo.update(command.id, changes);
        return result.ok
          ? { ok: true, value: `Completed #${command.id}` }
          : result;
      }
      case "retitle": {
        const result = this.repo.update(command.id, { title: command.title });
        return result.ok
          ? { ok: true, value: `Renamed #${command.id} to "${command.title}"` }
          : result;
      }
      case "remove":
        return this.repo.remove(command.id)
          ? { ok: true, value: `Removed #${command.id}` }
          : { ok: false, error: `Item ${command.id} not found` };
      default:
        return assertNever(command);
    }
  }

  summary(): Record<Priority, number> {
    const counts: Record<Priority, number> = { low: 0, medium: 0, high: 0 };
    for (const task of this.repo.all()) {
      if (!task.done) counts[task.priority]++;
    }
    return counts;
  }

  list(): string[] {
    return this.repo.all().map(t => `${t.done ? "[x]" : "[ ]"} #${t.id} ${t.title} (${t.priority})`);
  }
}

// ---------- Async source of tasks ----------
function wait(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function loadTasksFromServer(): Promise<string> {
  await wait(20);   // stands in for a fetch call
  return JSON.stringify([
    { title: "Write the lesson", priority: "high" },
    { title: "Review the code", priority: "medium" },
    { title: "Water the plants", priority: "low" },
  ]);
}

// ---------- Run it ----------
async function main(): Promise<void> {
  const manager = new TaskManager();

  const parsed = parseNewTasks(await loadTasksFromServer());
  if (!parsed.ok) {
    console.log("Could not load tasks:", parsed.error);
    return;
  }
  for (const task of parsed.value) {
    console.log(manager.run({ type: "add", task }));
  }

  console.log(manager.run({ type: "complete", id: 1 }));
  console.log(manager.run({ type: "retitle", id: 2, title: "Review the pull request" }));
  console.log(manager.run({ type: "remove", id: 99 }));

  console.log(manager.list().join("\n"));
  console.log("Open tasks by priority:", manager.summary());

  console.log(parseNewTasks("not json"));
  console.log(parseNewTasks('[{"title": "x", "priority": "urgent"}]'));
}

main();

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account