TExcelTAD
Home › TypeScript › TypeScript Mini Project

TypeScript Mini Project: Inventory Tracker

In this project you will build a small, fully typed inventory tracker for a shop. It records products, processes stock movements (deliveries, sales, corrections) and prints reports. Along the way you'll combine most of the course: literal unions, interfaces, discriminated unions, classes with private state, generics, utility types, Result objects and exhaustive switch statements.

We build it in four steps. Each playground is complete on its own, so you can run and modify any step.

Step What we add Main TypeScript features
1 Data model literal unions, interfaces, readonly, as const
2 The Inventory class classes, Map, Result<T, E>, Omit
3 Stock movements discriminated unions, never exhaustiveness
4 Reports generics, Record, keyof, sorting

Step 1: the data model

Start with the types. A category can only be one of a fixed list, so we derive a literal union from an as const array — the array is useful at runtime (for loops) and the type at compile time. Prices are stored in whole cents to avoid floating-point rounding errors.

ts · try it yourself
const CATEGORIES = ["drinks", "snacks", "stationery"] as const;
type Category = (typeof CATEGORIES)[number];   // "drinks" | "snacks" | "stationery"

interface Product {
  readonly sku: string;
  title: string;
  category: Category;
  priceCents: number;
  stock: number;
  minStock: number;
}

const tea: Product = {
  sku: "DRK-001",
  title: "Green tea",
  category: "drinks",
  priceCents: 350,
  stock: 24,
  minStock: 10,
};

const formatMoney = (cents: number) => `${(cents / 100).toFixed(2)}`;

console.log(CATEGORIES.join(", "));
console.log(`${tea.title} (${tea.category}) costs ${formatMoney(tea.priceCents)}`);
drinks, snacks, stationery
Green tea (drinks) costs $3.50

Try changing category: "drinks" to "drink" — the compiler rejects the typo immediately.

Step 2: the Inventory class

The inventory keeps products in a private Map keyed by SKU. Adding a product can fail (duplicate SKU, bad price), and that is an expected failure, so add returns a Result instead of throwing. New products always start with zero stock, so the input type is Omit<Product, "stock">.

ts · try it yourself
type Category = "drinks" | "snacks" | "stationery";

interface Product {
  readonly sku: string;
  title: string;
  category: Category;
  priceCents: number;
  stock: number;
  minStock: number;
}

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

class Inventory {
  #products = new Map<string, Product>();

  add(input: Omit<Product, "stock">): Result<Product> {
    if (this.#products.has(input.sku)) {
      return { ok: false, error: `SKU ${input.sku} already exists` };
    }
    if (!Number.isInteger(input.priceCents) || input.priceCents <= 0) {
      return { ok: false, error: `invalid price for ${input.sku}` };
    }
    const product: Product = { ...input, stock: 0 };
    this.#products.set(product.sku, product);
    return { ok: true, value: product };
  }

  get(sku: string): Product | undefined {
    return this.#products.get(sku);
  }

  all(): readonly Product[] {
    return [...this.#products.values()];
  }
}

const inv = new Inventory();
const attempts = [
  inv.add({ sku: "DRK-001", title: "Green tea", category: "drinks", priceCents: 350, minStock: 10 }),
  inv.add({ sku: "SNK-001", title: "Rice crackers", category: "snacks", priceCents: 199, minStock: 5 }),
  inv.add({ sku: "DRK-001", title: "Black tea", category: "drinks", priceCents: 300, minStock: 10 }),
  inv.add({ sku: "STA-001", title: "Notebook", category: "stationery", priceCents: 2.5, minStock: 3 }),
];

for (const r of attempts) {
  console.log(r.ok ? `added ${r.value.title}` : `rejected: ${r.error}`);
}
console.log(inv.all().map((p) => p.sku));
added Green tea
added Rice crackers
rejected: SKU DRK-001 already exists
rejected: invalid price for STA-001
[ 'DRK-001', 'SNK-001' ]

Because all() returns readonly Product[], code outside the class can't push into the list or sort it in place.

Step 3: stock movements

Every change to stock is described by a movement. The three kinds carry different data, which is exactly what a discriminated union is for. The apply method switches on kind, and the never check in default guarantees that a new movement kind can't be forgotten:

ts · try it yourself
interface Product {
  readonly sku: string;
  title: string;
  stock: number;
}

type Movement =
  | { kind: "delivery"; sku: string; quantity: number; supplier: string }
  | { kind: "sale"; sku: string; quantity: number }
  | { kind: "correction"; sku: string; newStock: number; reason: string };

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

function apply(product: Product, m: Movement): Result<number> {
  switch (m.kind) {
    case "delivery":
      product.stock += m.quantity;
      return { ok: true, value: product.stock };
    case "sale":
      if (m.quantity > product.stock) {
        return { ok: false, error: `only ${product.stock} ${product.title} left` };
      }
      product.stock -= m.quantity;
      return { ok: true, value: product.stock };
    case "correction":
      product.stock = m.newStock;
      return { ok: true, value: product.stock };
    default: {
      const unknownMovement: never = m;
      throw new Error(`unknown movement ${JSON.stringify(unknownMovement)}`);
    }
  }
}

const tea: Product = { sku: "DRK-001", title: "Green tea", stock: 0 };
const log: Movement[] = [
  { kind: "delivery", sku: "DRK-001", quantity: 30, supplier: "Lam Dong Farms" },
  { kind: "sale", sku: "DRK-001", quantity: 12 },
  { kind: "sale", sku: "DRK-001", quantity: 25 },
  { kind: "correction", sku: "DRK-001", newStock: 17, reason: "one box damaged" },
];

for (const m of log) {
  const r = apply(tea, m);
  console.log(m.kind.padEnd(10), r.ok ? `stock = ${r.value}` : `FAILED: ${r.error}`);
}
delivery   stock = 30
sale       stock = 18
sale       FAILED: only 18 Green tea left
correction stock = 17

Step 4: reports — the complete program

Finally, put everything together and add reports. sumBy is a small generic helper whose key parameter only accepts property names whose values are numbers. Record<Category, number> guarantees that the per-category totals have an entry for every category, even an empty one.

ts · try it yourself
const CATEGORIES = ["drinks", "snacks", "stationery"] as const;
type Category = (typeof CATEGORIES)[number];

interface Product {
  readonly sku: string;
  title: string;
  category: Category;
  priceCents: number;
  stock: number;
  minStock: number;
}

type Movement =
  | { kind: "delivery"; sku: string; quantity: number }
  | { kind: "sale"; sku: string; quantity: number }
  | { kind: "correction"; sku: string; newStock: number };

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

type NumericKeys<T> = { [K in keyof T]: T[K] extends number ? K : never }[keyof T];

function sumBy<T>(items: readonly T[], key: NumericKeys<T>): number {
  return items.reduce((acc, item) => acc + (item[key] as number), 0);
}

const money = (cents: number) => `${(cents / 100).toFixed(2)}`;

class Inventory {
  #products = new Map<string, Product>();

  add(input: Omit<Product, "stock">): Result<Product> {
    if (this.#products.has(input.sku)) return { ok: false, error: `duplicate ${input.sku}` };
    const product: Product = { ...input, stock: 0 };
    this.#products.set(product.sku, product);
    return { ok: true, value: product };
  }

  apply(m: Movement): Result<number> {
    const p = this.#products.get(m.sku);
    if (!p) return { ok: false, error: `unknown SKU ${m.sku}` };
    switch (m.kind) {
      case "delivery":
        p.stock += m.quantity;
        break;
      case "sale":
        if (m.quantity > p.stock) return { ok: false, error: `not enough ${p.title}` };
        p.stock -= m.quantity;
        break;
      case "correction":
        p.stock = m.newStock;
        break;
      default: {
        const never: never = m;
        throw new Error(`unhandled ${JSON.stringify(never)}`);
      }
    }
    return { ok: true, value: p.stock };
  }

  lowStock(): Product[] {
    return this.all().filter((p) => p.stock < p.minStock);
  }

  valueByCategory(): Record<Category, number> {
    const totals = Object.fromEntries(CATEGORIES.map((c) => [c, 0])) as Record<Category, number>;
    for (const p of this.all()) totals[p.category] += p.stock * p.priceCents;
    return totals;
  }

  all(): Product[] {
    return [...this.#products.values()];
  }
}

const inv = new Inventory();
inv.add({ sku: "DRK-001", title: "Green tea", category: "drinks", priceCents: 350, minStock: 10 });
inv.add({ sku: "DRK-002", title: "Mango juice", category: "drinks", priceCents: 275, minStock: 12 });
inv.add({ sku: "SNK-001", title: "Rice crackers", category: "snacks", priceCents: 199, minStock: 5 });
inv.add({ sku: "STA-001", title: "Notebook", category: "stationery", priceCents: 250, minStock: 3 });

const movements: Movement[] = [
  { kind: "delivery", sku: "DRK-001", quantity: 30 },
  { kind: "delivery", sku: "DRK-002", quantity: 20 },
  { kind: "delivery", sku: "SNK-001", quantity: 15 },
  { kind: "sale", sku: "DRK-002", quantity: 11 },
  { kind: "sale", sku: "SNK-001", quantity: 16 },
  { kind: "sale", sku: "XXX-999", quantity: 1 },
  { kind: "correction", sku: "DRK-001", newStock: 28 },
];

const errors = movements.map((m) => inv.apply(m)).flatMap((r) => (r.ok ? [] : [r.error]));
console.log("Errors:", errors);

console.log("\nSKU      Title           Stock   Value");
for (const p of inv.all()) {
  console.log(
    `${p.sku}  ${p.title.padEnd(14)} ${String(p.stock).padStart(5)} ${money(p.stock * p.priceCents).padStart(8)}`
  );
}

console.log("\nUnits in stock:", sumBy(inv.all(), "stock"));
console.log("Low stock:", inv.lowStock().map((p) => p.title).join(", "));

const byCategory = inv.valueByCategory();
for (const c of CATEGORIES) console.log(`${c.padEnd(11)} ${money(byCategory[c])}`);
Errors: [ 'not enough Rice crackers', 'unknown SKU XXX-999' ]

SKU      Title           Stock   Value
DRK-001  Green tea         28   $98.00
DRK-002  Mango juice        9   $24.75
SNK-001  Rice crackers     15   $29.85
STA-001  Notebook           0    $0.00

Units in stock: 52
Low stock: Mango juice, Notebook
drinks      $122.75
snacks      $29.85
stationery  $0.00

Try sumBy(inv.all(), "title") — it fails to compile, because title is a string property and NumericKeys<Product> only contains "priceCents" | "stock" | "minStock".

Ideas to extend the project

  • Add a "return" movement kind (a customer brings an item back). Notice how the compiler points to every switch that must handle it.
  • Store the movement history and add a historyFor(sku) method returning readonly Movement[].
  • Add a discountPercent?: number field and make the value report respect it.
  • Convert apply to async and simulate saving each movement with a Promise.

Tip: Notice how little code needed defensive runtime checks. The types (literal unions, Record, discriminated unions) make whole classes of mistakes impossible, so the remaining checks are only for things that really depend on data — like selling more than you have.

Test yourself

Why does the project derive Category from an as const array instead of writing the union by hand?

  1. It is required for Map keys
  2. The array exists at runtime (for loops) and the union type stays in sync with it
  3. Unions can't contain strings
  4. It makes the code run faster

What makes adding a new movement kind safe?

  1. The Result type
  2. The never assignment in the switch's default branch
  3. The private #products field
  4. Omit<Product, "stock">

Why does valueByCategory return Record<Category, number> rather than Record<string, number>?

  1. It guarantees a value for every category and rejects unknown keys
  2. Records with string keys are not allowed
  3. It saves memory
  4. It allows negative numbers