Skip to content

Checkpoint: Reusable Lookup

The Course
•
25 min study

Build one small helper that works for two kinds of records. A session has id, topic and minutes. A book has id, title and pages. Both can be looked up by a string id, but callers should still know which full record they receive.

Searching a list with find scans every record on every lookup. Your task is to build a lookup table once: a helper, indexById, that takes a list of records and returns an object keyed by each record's id. One helper must work for both sessions and books, and a lookup in the table must give back the full record type, so table["s1"]?.topic compiles for sessions and table["b1"]?.title for books. If two records share an id, the later one wins.

You design the signature. Decide what the type parameter stands for, what the constraint must require (and must not), and what type the returned table has. Day 4's Record type and this day's constraints are all you need. Do not use any, and do not return only { id: string } records.

Spend the final five minutes explaining your signature: what T preserves, what the constraint requires, and why a lookup of a missing id still has to be handled.

Predict, check, then run

Before running, write down the output and explain which information the checker knows. Click Check types first, then Check & run.

Predict, then runTypeScript
function echo<T>(value: T): T {
  return value;
}

const session = echo({ id: "s1", topic: "Types" });

console.log(session.topic);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
Types

Acceptance cases before you code

Before you write indexById, decide what each case below should print. Each one checks a different part of your signature or loop.

Case to tryWhat your result should demonstrate
Session table, id "s1"?.topic compiles and prints the session's topic
Book table with two records sharing id "b2"The later record's title is printed
Book table, id "none"The lookup is undefined; ?? "Missing" prints Missing without a cast
An empty listThe table has no keys
Reading .title from a session table entryCheck types rejects it

If your return type were Record<string, { id: string }>, the first case would stop compiling: the table forgot the topic. If it were any, the last case would compile and quietly print undefined. Only a type parameter carried from the list into the table passes every case.

Your turn

Exercise

Checkpoint: Reusable Lookup: practice

Implement indexById as described above. Build a session table from [{ id: "s1", topic: "Types", minutes: 25 }] and a book table from Handbook (b1), Old (b2) and Guide (b2). Print Types, Guide and Missing for the three lookups in the acceptance table, then 0 for the number of keys in the table built from an empty list.

Your workspaceTypeScript
// Design the signature, build the table in a loop, then test both record shapes.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

The body only reads id, so the constraint needs nothing else. The type parameter is what lets the table remember the rest of each record.

Hint 2: a first step

Start the body with an empty object whose type is a Record from string keys to the record type, then fill it in a for/of loop.

Show one solution
One possible solutionTypeScript
function indexById<T extends { id: string }>(
  items: readonly T[]
): Record<string, T> {
  const table: Record<string, T> = {};
  for (const item of items) {
    table[item.id] = item;
  }
  return table;
}

const sessions = indexById([{ id: "s1", topic: "Types", minutes: 25 }]);
const books = indexById([
  { id: "b1", title: "Handbook", pages: 120 },
  { id: "b2", title: "Old", pages: 10 },
  { id: "b2", title: "Guide", pages: 80 }
]);

console.log(sessions["s1"]?.topic ?? "Missing");
console.log(books["b2"]?.title ?? "Missing");
console.log(books["none"]?.title ?? "Missing");
console.log(Object.keys(indexById([])).length);

Enable JavaScript to edit and type-check this example.

Text
Types
Guide
Missing
0

T is chosen by each call, so sessions is a Record<string, { id: string; topic: string; minutes: number }> and books a record of books; that is what makes .topic and .title legal. The constraint { id: string } is exactly what table[item.id] needs. The table has string keys, so with indexed-access checking every lookup is T | undefined, and ?. with ?? handles the missing id. Assigning in list order is what makes the later "b2" win.

Change it and explain it

Try reading title from a session table entry and confirm the checker rejects it. Change the return type to Record<string, { id: string }> and read the new diagnostic. Then explain when a table is worth building instead of calling find: how many lookups, and what happens to the table if the list changes later?

Was this article helpful?

Your response is saved on this device.