Skip to content
Tutorials Center
My learning

Topics

Lesson 89 of 96 Β· Projects

Project: Contact Manager

Build a contact manager in TypeScript - a generic repository with create, read, update and delete, field validation with mapped types, search, sorting and persistence through a storage interface.

A contact manager is the "hello world" of data-driven apps: Create, Read, Update and Delete records, validate what users type, find people quickly and save everything. Nearly every business application is a bigger version of this program, so it is a great way to practice the TypeScript tools that scale: generics, utility types, mapped types and small interfaces for storage.

You will build it in three stages. First a reusable generic repository that knows nothing about contacts. Then the contact type with validation that reports errors per field. Finally search, sorting and persistence, with the storage hidden behind an interface so the same code works with localStorage in a browser and an in-memory fake here.

Stage 1: a generic repository

The repository stores records that have an id. Its methods use utility types to say exactly what each operation accepts: creating takes the record without an id (the repository assigns it), and updating takes a partial record.

TypeScript Stage 1: Repository<T> with Omit and Partial

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.

Repository<T> is useful for any entity: a Product repository is one line. Omit<T, 'id'> makes it a compile error to supply an id when creating, and Patch<T> makes it an error to change an id when updating. Both internal as T assertions are justified by comments, and contained in two lines so the public API stays fully typed. Methods return readonly T[] so callers cannot mutate the repository's list.

Stage 2: validation that reports errors per field

Real forms need good error messages: not "invalid", but "email: must contain @". A mapped type lets us declare one validator per field of the input and get back errors keyed by the same field names.

TypeScript Stage 2: a Validators<T> mapped type and typed errors

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.

Validators<T> uses -? to strip optionality, so every field, even the optional phone, needs a validator. Add a company field to ContactInput and the compiler lists the validator you forgot. Errors<T> is Partial<Record<keyof T, string>>, so a UI can render errors.email without any casting. Compare this hand-built approach with schema libraries in Validating Data with Zod: a library gives you more features, while building it once shows what they do.

We want one function that validates and then creates, returning a result that must be checked. Use a discriminated union:

TypeScript
type SaveResult =
  | { ok: true; contact: Contact }
  | { ok: false; errors: Errors<ContactInput> };

function addContact(input: ContactInput): SaveResult {
  const errors = validate(input, contactValidators);
  if (Object.keys(errors).length > 0) return { ok: false, errors };
  return { ok: true, contact: contacts.create(input) };
}

Callers must check result.ok before reading contact, which stops "saved" notifications for contacts that never saved.

Stage 3: search, sorting and persistence

Search should be forgiving: ignore case and accents, and match any word in any text field. Sorting should work for any field. Persistence should not care where bytes go: we hide storage behind a tiny interface that localStorage already satisfies.

TypeScript Stage 3: search, typed sorting and persistence through an interface

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.

Three design choices deserve attention. First, SortableKey is a literal union, not keyof Contact, because only some fields are sortable strings: a[key].localeCompare would not compile for tags or an optional phone, and the union makes that mistake impossible. Second, fold removes accents with Unicode normalization (NFD splits Γ© into e plus a combining mark, and \p{M} removes the marks), so searching "emile" finds "Γ‰mile". Third, load never trusts what is in storage: it parses to unknown and keeps only values that pass the isContact type guard, so a corrupted or tampered entry is dropped instead of crashing the app later.

In a browser you pass localStorage itself, because it already has getItem and setItem with those signatures:

TypeScript
const contacts = load(localStorage);
// ...edit the list...
save(localStorage, contacts);

Remember that localStorage is unavailable inside the sandboxed editors on this site, which is exactly why the interface helps: the logic never mentions the browser.

Ideas to extend it

  • Add soft delete with a deletedAt?: Date field and an all() that hides deleted records.
  • Make Repository<T> emit change events and have the UI subscribe (see Project: Event System).
  • Add duplicate detection: refuse a second contact with the same email, reporting it as a validation error.
  • Import and export vCard or CSV, validating each row with the same validators.
  • Debounce the search box input to avoid filtering on every key press.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does Omit<T, 'id'> express in create(data: Omit<T, 'id'>)?

    Omit removes the listed keys from a type, so creating a record cannot supply an id.
  2. 2. What does the -? modifier do in [K in keyof T]-?: ...?

    -? strips optionality, so even optional fields like phone need a validator.
  3. 3. Why does load parse into unknown and filter with isContact?

    Anything read from storage or the network is untrusted; a type guard narrows only valid values.
  4. 4. Why is SortableKey defined as 'name' | 'email' rather than keyof Contact?

    tags is an array and phone is optional, so a[key].localeCompare would not type check for them.
  5. 5. Why pass a KeyValueStore interface instead of using localStorage directly?

    localStorage already satisfies the interface, and tests can pass an in-memory fake.

Summary

  • A generic Repository<T extends Entity> gives CRUD for any record type; Omit and Partial describe create and update inputs precisely.
  • A mapped type like Validators<T> with -? forces a validator for every field, and Errors<T> keys messages by field name.
  • Return a discriminated SaveResult so callers must check for errors before using the contact.
  • Normalize text (NFD plus removing marks) for forgiving search, and restrict sort keys with a literal union.
  • Hide storage behind a small interface, and treat loaded data as unknown validated by a type guard.

Next: Project: Tic Tac Toe