Skip to content
Tutorials Center
My learning

Topics

Lesson 78 of 96 ยท Projects

Project: Inventory with Generics

Build a typed inventory in TypeScript - a generic Repository, DTO types made with Omit, Partial and Pick, validation of unknown JSON with type guards, and reports.

Almost every business application has the same core: records with ids, a place to store them, rules about what a valid record looks like, and reports over the data. In this project you'll build that core for a small warehouse, with products, suppliers, stock levels and reorder warnings, and you'll write it once, generically, so the same code stores any kind of record.

Along the way you'll use generics and generic constraints for a reusable Repository<T, Id>, utility types to derive "create" and "update" shapes from one model, type guards to turn untrusted JSON into typed records, and a few generic helpers for reports. There are four stages, and each one is a complete program you can run and change.

The plan

Stage What you build Main TypeScript ideas
1 A generic in-memory repository used for two record types Generic classes, constraints, Omit, Supplier['id']
2 Create and update shapes (DTOs), read-only results Partial, Pick, Readonly, intersections, defaults
3 Importing products from JSON with validation unknown, type guards, a generic Result<T, E>
4 Stock reports Record<Category, โ€ฆ>, Object.groupBy, keyof columns

All data lives in memory, so every run starts fresh. In a real app, the repository class would be backed by a database, but its type would stay the same, which is exactly the point of hiding storage behind an interface.

Stage 1: a generic repository

A repository stores records by id. Products get numeric ids from a counter; suppliers get readable codes like SUP-001. Instead of writing two storage classes, write one class with two type parameters: T, the record type, and Id, the type of its id. The constraint T extends { readonly id: Id } says "whatever T is, it must have an id of type Id", so the class can safely read item.id.

TypeScript Stage 1: one repository class for two record types

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 two repositories share every line of code but not their types: products.get accepts a number, suppliers.get a string. The // @ts-expect-error line proves it. That comment tells the compiler "the next line must be an error", so the program still compiles and runs. Remove the comment and you get error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. If the line ever stopped being an error, @ts-expect-error itself would complain.

A few things to notice:

  • create takes Omit<T, 'id'>. Callers pass everything except the id, because the repository generates it. Try leaving out stock in one of the products.create calls: TypeScript lists the missing property.
  • supplierId: Supplier['id'] is an indexed access type. If supplier ids ever become numbers, Product updates automatically.
  • The one as T is honest about a real limitation. { ...data, id } has type Omit<T, 'id'> & { id: Id }, and for some exotic T (one whose id is a narrower literal type, say) that isn't the same as T. Keeping the assertion inside the class means no caller ever needs one.
  • #items is private and readonly. Nobody outside can replace the map or bypass create.

Stage 2: create and update shapes

A model type like Product describes a stored record. The data that flows into the system is usually shaped differently: a new product has no id yet and may leave some fields to defaults, and an update changes only a few fields. These shapes are often called DTOs (data transfer objects). Writing them by hand means three copies of the same fields to keep in sync. Deriving them with utility types means one source of truth:

TypeScript
type NewProduct = Omit<Product, 'id'>; // everything except the id
type ProductInput = Omit<NewProduct, 'stock' | 'reorderLevel'> &
  Partial<Pick<NewProduct, 'stock' | 'reorderLevel'>>; // those two become optional
type ProductPatch = Partial<Omit<Product, 'id'>>; // any subset, never the id
type ProductSummary = Pick<Product, 'id' | 'name' | 'stock'>;

Stage 2 adds an update method that accepts a patch, returns records as Readonly<T> so callers can't change stored data behind the repository's back, and fills in defaults for new products.

TypeScript Stage 2: DTO types, updates and read-only results

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 "careless patch" shows why update filters out undefined values: in the output, the name changed but the stock is still 25. With our editor's settings, { stock: undefined } is a valid ProductPatch, because an optional property accepts undefined unless exactOptionalPropertyTypes is on. Without the filter, that patch would replace a real stock count with undefined, a value the Product type says can't exist. The runtime filter and the compiler flag are two layers of the same defense; real projects should use both.

The @ts-expect-error at the end shows Readonly<T> in action: assigning to lamp.stock is error TS2540, Cannot assign to 'stock' because it is a read-only property. (The assignment still happened at runtime, since Readonly is compile-time only, which is one more reason to give stored objects to callers as copies in real code.)

The derived types also reject mistakes in patches. This small program fails on purpose:

TypeScript What a patch may not contain (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.

The compiler reports three errors, one per mistake:

TEXT
main.ts(11,5): error TS2353: Object literal may only specify known properties, and 'id' does not exist in type 'Partial<Omit<Product, "id">>'.
main.ts(12,5): error TS2561: Object literal may only specify known properties, but 'stok' does not exist in type 'Partial<Omit<Product, "id">>'. Did you mean to write 'stock'?
main.ts(13,5): error TS2322: Type 'string' is not assignable to type 'number'.

Because Omit removed id, a patch can't change an id; the excess property check catches the typo (and suggests the fix); and the field types still apply even though every field is optional. Notice that the messages spell out the alias as Partial<Omit<Product, "id">>: TypeScript often shows how a derived type was built rather than the alias name you gave it.

Stage 3: importing products from JSON

So far every product came from your own code, where the compiler checked it. Real inventory data arrives from outside: a supplier's price list, a spreadsheet export, an HTTP request. That data is unknown until proven otherwise, so this stage validates each record before it reaches the repository.

The validator returns a generic Result<T, E>: either { ok: true, value } or { ok: false, error }. Instead of stopping at the first problem, it collects all problems with a record, which is what users of an import feature want. Each field is read by a small check that returns either a correctly typed value or undefined, so the final object is built without a single assertion.

The import file is a string inside the program (our editor has no file uploads), with one JSON object per line, a format known as JSON Lines.

TypeScript Stage 3: validating an import file

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.

Line 3 shows why collecting every issue matters: the empty name, the unknown category and the fractional price are all reported at once, so the person fixing the file doesn't have to rerun the import three times. Line 2 has no stock, so it gets the default of 0, and line 4 is rejected for both a negative stock and a supplier that doesn't exist.

Look at how the validator gets its types without as:

  • isRecord(value) narrows unknown to Record<string, unknown>, so value.name can be read, but it's still unknown.
  • Each field check narrows further: inside typeof value.name === 'string' && ..., value.name is a string. isCategory is a type predicate, so value.category becomes Category.
  • Each local (name, category, โ€ฆ) has a type like string | undefined. The big if at the end rules out every undefined, so after it TypeScript knows all six are defined and the object literal matches NewProduct exactly.

In production code, schema libraries such as Zod or Valibot write this kind of validator for you: you describe the shape once and get both the runtime check and the TypeScript type. Typing APIs and JSON Data compares them. Writing one by hand, as here, is the best way to understand what they do.

Stage 4: reports

With trustworthy data in the repository, reports become simple functions. This stage adds three:

  1. Totals per category, typed as Record<Category, Totals>. Because the key type is the Category union, the object must have an entry for every category: add 'garden' to CATEGORIES and this function stops compiling until you handle it.
  2. A reorder list: products at or below their reorder level, with the supplier's name looked up through the supplier repository.
  3. The most valuable stock, using a small generic topBy helper.

A generic printTable prints rows of any type. Its columns parameter uses keyof T, so you can only ask for columns that really exist on the rows, and the compiler checks the names.

To keep the listing focused, this stage creates its products directly instead of importing them; in the full application they would arrive through stage 3's validator.

TypeScript Stage 4: inventory reports

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.

Each report is a few lines, because the hard work (valid, typed data) was done earlier. Some type-level details deserve a closer look:

  • Object.groupBy (ES2024) returns Partial<Record<Category, Product[]>>. TypeScript marks every group as possibly missing, because a category with no products has no key at all. That's why totals writes groups[category] ?? [].
  • Record<Category, Totals> makes the return statement list all three categories. The compiler checks completeness for you.
  • Column<T> with key: keyof T ties column names to the row type. In the reorder table, T is inferred from reorder as { name: string; stock: number; level: number; supplier: string }, so { key: 'suplier', โ€ฆ } would be a compile error.
  • Inferred row types. The .map((p) => ({ โ€ฆ })) calls create new object types on the fly; you never had to name ReorderRow. Inference (Type Inference) carries the shape into printTable.

Ideas for extending the inventory

  • Add a Repository.findBy(predicate) method and an index of products by supplier.
  • Make ids branded types (type ProductId = number & { readonly __brand: 'ProductId' }) so a supplier's numeric id can never be passed where a product id is expected (Advanced Type-Level Programming).
  • Add stock movements ({ kind: 'received' | 'sold'; productId; quantity }) as a discriminated union and compute stock from them.
  • Turn the repository into an interface Repository<T, Id> with two implementations: the in-memory one and a fake "slow" one that returns promises.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given class Repository<T extends { readonly id: Id }, Id extends string | number>, which line is a compile error for const repo = new Repository<Product, number>(...)?

    The Id type parameter is number for this repository, so get only accepts numbers. A string argument is error TS2345.
  2. 2. What does Partial<Omit<Product, 'id'>> describe?

    Omit removes id, then Partial makes every remaining property optional, which is exactly the shape of an update patch.
  3. 3. Without exactOptionalPropertyTypes, is { stock: undefined } a valid Partial<Product>?

    Optional properties allow undefined unless exactOptionalPropertyTypes is on, so a patch could erase a field. The runtime filter (and the compiler flag) prevent that.
  4. 4. After if (isRecord(value)) where isRecord returns value is Record<string, unknown>, what is the type of value.name?

    The guard proves value is an object with string keys, but each property is still unknown. A second check such as typeof value.name === 'string' is needed.
  5. 5. Why does categoryTotals return Record<Category, Totals> instead of Record<string, Totals>?

    With the Category union as key type, leaving out a category (or adding a new one to CATEGORIES) makes the return statement a compile error.

Summary

  • A generic class with a constraint (T extends { readonly id: Id }) gives you one storage implementation with fully typed ids for every record type.
  • Derive input shapes from the model: Omit<T, 'id'> for creation, Partial<Omit<T, 'id'>> for patches, Pick for summaries, Readonly<T> for results.
  • Optional properties accept undefined; filter it out at runtime and enable exactOptionalPropertyTypes to stop patches from erasing data.
  • Validate outside data as unknown, narrow field by field with type guards, collect every issue, and return a Result<T, E>; then no assertions are needed.
  • Record<Union, V> forces complete lookup tables; Object.groupBy returns a Partial record, so handle missing groups.
  • keyof T in helper parameters (like table columns) keeps generic utilities checked against the real row types.

Next: Project: Type-Safe Event Emitter