Skip to lesson

TypeScript · Lesson 42 of 42

Final project: a typed inventory manager

Build a small inventory manager that brings the course together: types, a generic result, a class, discriminated union commands, utility types and checks.

Beginner to advanced·25 min·Real-world TypeScript·Updated 2026-11-24

UNDERSTAND IT. THEN TRY IT.

What you can do after this lesson

You will have built a complete, small program that uses most of what the course taught, and you will have a template for how to structure the next one. The project is an inventory manager for a shop: it stores products, accepts commands that change stock, and reports what is left. Everything is typed, and the compiler finds mistakes at every step.

What we are building

The program has four parts:

  1. Types for items, commands and results.
  2. A class that holds the inventory and enforces the rules.
  3. A command processor that applies a list of commands.
  4. A report of the final stock.

Create a project (see the setup lesson), turn on strict, and put the code below into one file, inventory.ts, building it up in the order shown. Each step runs on its own.

Step 1: the types

Start with the shapes. Item data has an identifier we generate, and a NewItem is the same without it, derived with a utility type:

typescript
type Category = "stationery" | "electronics" | "books";

type Item = {
  readonly id: number;
  name: string;
  price: number;
  quantity: number;
  category: Category;
};

type NewItem = Omit<Item, "id">;
type ItemUpdate = Partial<Omit<Item, "id">>;

const pen: NewItem = { name: "Pen", price: 2.5, quantity: 100, category: "stationery" };
console.log(pen);
result
{ name: 'Pen', price: 2.5, quantity: 100, category: 'stationery' }

Notice what the types already prevent: a misspelt category is an error, the id cannot be set by the caller or changed later, and an update can change any field except the identifier.

Step 2: results instead of exceptions

Operations here can fail in expected ways, such as removing more stock than exists. We model that with a generic result type, as in the error handling lesson:

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

const success = <T,>(value: T): Result<T> => ({ ok: true, value });
const failure = (error: string): Result<never> => ({ ok: false, error });

function divide(a: number, b: number): Result<number> {
  return b === 0 ? failure("division by zero") : success(a / b);
}

console.log(divide(10, 4), divide(1, 0));
result
{ ok: true, value: 2.5 } { ok: false, error: 'division by zero' }

The type Result<never> returned by failure fits into any Result<T>, because a failure carries no value.

Step 3: the Inventory class

The class owns the data and the rules. The items are private, and callers use methods that return results:

typescript
type Category = "stationery" | "electronics" | "books";
type Item = { readonly id: number; name: string; price: number; quantity: number; category: Category };
type NewItem = Omit<Item, "id">;
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

class Inventory {
  private items = new Map<number, Item>();
  private nextId = 1;

  add(data: NewItem): Result<Item> {
    if (data.price < 0 || data.quantity < 0) {
      return { ok: false, error: "price and quantity must not be negative" };
    }
    const item: Item = { id: this.nextId++, ...data };
    this.items.set(item.id, item);
    return { ok: true, value: item };
  }

  remove(id: number, amount: number): Result<Item> {
    const item = this.items.get(id);
    if (!item) return { ok: false, error: `item ${id} not found` };
    if (amount > item.quantity) {
      return { ok: false, error: `only ${item.quantity} of ${item.name} in stock` };
    }
    item.quantity -= amount;
    return { ok: true, value: item };
  }

  restock(id: number, amount: number): Result<Item> {
    const item = this.items.get(id);
    if (!item) return { ok: false, error: `item ${id} not found` };
    item.quantity += amount;
    return { ok: true, value: item };
  }

  list(): readonly Item[] {
    return [...this.items.values()];
  }

  totalValue(): number {
    return this.list().reduce((sum, item) => sum + item.price * item.quantity, 0);
  }
}

const inventory = new Inventory();
const added = inventory.add({ name: "Pen", price: 2.5, quantity: 10, category: "stationery" });
console.log(added.ok ? `added #${added.value.id}` : added.error);
console.log(inventory.remove(1, 4).ok, inventory.remove(1, 50).ok, inventory.remove(9, 1).ok);
console.log(inventory.totalValue());
result
added #1
true false false
15

(In the class, the repeated type definitions at the top only make this step run on its own. In your file they come from Step 1.) Notice several earlier lessons at work: a private Map, a generic Result, a return type readonly Item[] that stops callers from changing the list, and a discriminated union narrowed with .ok.

Step 4: commands as a discriminated union

Instead of calling methods directly, we describe each action as a command object, a value that can be stored, logged or sent over a network. Each command has a type tag:

typescript
type Command =
  | { type: "add"; name: string; price: number; quantity: number }
  | { type: "remove"; id: number; amount: number }
  | { type: "restock"; id: number; amount: number };

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

function describe(command: Command): string {
  switch (command.type) {
    case "add":
      return `add ${command.quantity} x ${command.name}`;
    case "remove":
      return `remove ${command.amount} of #${command.id}`;
    case "restock":
      return `restock #${command.id} by ${command.amount}`;
    default:
      return assertNever(command);
  }
}

console.log(describe({ type: "add", name: "Notebook", price: 4, quantity: 20 }));
console.log(describe({ type: "remove", id: 1, amount: 3 }));
result
add 20 x Notebook
remove 3 of #1

If someone adds a fourth command to the union and forgets to handle it here, assertNever stops the program from compiling.

Step 5: putting it together

Now connect the commands to the inventory, process a list, and print a report. This is the complete program, with every step in one block, so you can run it as it stands:

typescript
type Category = "stationery" | "electronics" | "books";
type Item = { readonly id: number; name: string; price: number; quantity: number; category: Category };
type NewItem = Omit<Item, "id">;
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

type Command =
  | { type: "add"; name: string; price: number; quantity: number; category: Category }
  | { type: "remove"; id: number; amount: number }
  | { type: "restock"; id: number; amount: number };

class Inventory {
  private items = new Map<number, Item>();
  private nextId = 1;

  add(data: NewItem): Result<Item> {
    if (data.price < 0 || data.quantity < 0) {
      return { ok: false, error: "price and quantity must not be negative" };
    }
    const item: Item = { id: this.nextId++, ...data };
    this.items.set(item.id, item);
    return { ok: true, value: item };
  }

  change(id: number, delta: number): Result<Item> {
    const item = this.items.get(id);
    if (!item) return { ok: false, error: `item ${id} not found` };
    if (item.quantity + delta < 0) {
      return { ok: false, error: `only ${item.quantity} of ${item.name} in stock` };
    }
    item.quantity += delta;
    return { ok: true, value: item };
  }

  list(): readonly Item[] {
    return [...this.items.values()];
  }
}

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

function apply(inventory: Inventory, command: Command): Result<Item> {
  switch (command.type) {
    case "add":
      return inventory.add({
        name: command.name,
        price: command.price,
        quantity: command.quantity,
        category: command.category,
      });
    case "remove":
      return inventory.change(command.id, -command.amount);
    case "restock":
      return inventory.change(command.id, command.amount);
    default:
      return assertNever(command);
  }
}

const inventory = new Inventory();
const commands: Command[] = [
  { type: "add", name: "Pen", price: 2.5, quantity: 10, category: "stationery" },
  { type: "add", name: "Atlas", price: 18, quantity: 3, category: "books" },
  { type: "remove", id: 1, amount: 4 },
  { type: "remove", id: 2, amount: 5 },
  { type: "restock", id: 2, amount: 7 },
  { type: "remove", id: 99, amount: 1 },
];

for (const command of commands) {
  const result = apply(inventory, command);
  console.log(result.ok ? `ok: ${result.value.name} now ${result.value.quantity}` : `error: ${result.error}`);
}

const byCategory: Record<Category, number> = { stationery: 0, electronics: 0, books: 0 };
for (const item of inventory.list()) {
  byCategory[item.category] += item.quantity;
}
console.log(byCategory);
result
ok: Pen now 10
ok: Atlas now 3
ok: Pen now 6
error: only 3 of Atlas in stock
ok: Atlas now 10
error: item 99 not found
{ stationery: 6, electronics: 0, books: 10 }

Read the output line by line against the commands. The third command removes four pens, the fourth tries to remove five atlases when only three exist and fails, the fifth restocks, and the last refers to an item that does not exist. Every failure came back as a value that the loop handled, not as a crash.

What the compiler is doing for you

Count the mistakes that this program makes impossible:

  • A misspelt category or command type.
  • Passing an id or an amount as a string instead of a number.
  • Changing an item's id after creation.
  • Forgetting to handle a new command.
  • Reading result.value without checking result.ok.
  • Adding to or removing from the list that list() returns, because it is a readonly array. (The items inside are ordinary objects, so a caller could still change an item's quantity; the types protect the class's rules only as far as you model them.)

That is the value of the whole course: not that code never fails, but that whole classes of mistakes are found by the compiler before the program ever runs.

Common mistakes

Putting everything in one giant function. Split the rules (the class), the commands (the union) and the reporting.

Using any to move faster. The project is small enough to type fully. Practise on it.

Skipping validation at the edge. In a real program, commands would arrive as JSON. Validate them with a parse function before applying them, as the API data lesson showed.

Forgetting the default branch with assertNever. It is what protects you the day you add a command.

Exercise

Extend the project in these ways, letting the compiler guide you. Add a "rename" command and watch assertNever point at every place that needs updating. Add an ItemUpdate command using Partial. Write parseCommand(data: unknown): Result<Command> that validates JSON input. Add two tests with node:test for remove and restock. Finally, enable noUncheckedIndexedAccess and fix whatever it reports.

Congratulations: you have completed the TypeScript course. Take the final exam to earn your certificate, and keep the habit of reading compiler errors slowly. They are the language teaching you.

KNOWLEDGE CHECK

A quick check. You’ve got this.

Try each question. Every answer comes with an explanation.

0 / 4 understood
01 Why is a discriminated union a good fit for commands such as add, remove and restock?
02 What does assertNever(command) in the default branch of a switch give you?
03 How can NewItem be derived from Item without repeating fields?
04 Why return a Result from an operation like removing stock?

Ready for the next small win?

Mark the lesson complete when you are ready.

Final exam and certificate

Finish all 42 lessons to unlock a 15-question exam on TypeScript. Pass it and you get a certificate with a public link you can share.

Sign in to take the exam
Course navigation

Frontend

TypeScript tutorial

Add types to JavaScript to catch mistakes before your code runs, from your first annotation to generics and real projects.

Your progress 0/42
Learning something new?Explore all courses