A chart needs label/value pairs from any list of records. Build pairs(records, labelKey, valueKey): for each record, return a two-item pair of the label property and the value property, in input order. The input list may be readonly and must not be changed.
The behavior is one map. The task is the signature, and you design it: no any, no assertions, and no union that forgets which key was chosen. For books with title:string and pages:number, pairs(books, "title", "pages") must give pairs whose first position supports string methods and whose second supports arithmetic; swapping the keys must swap those types. A key the records don't have, such as "author", must be a compile error.
You need three Day 2 ideas at once: keys constrained by keyof, indexed access types, and a tuple type for each pair.
Predict, run, and explain
Write down what the program prints before you run it. Use Check types first; the program runs only when the real compiler accepts it.
type Book = {
title: string;
pages: number;
};
type PageCount = Book["pages"];
const count: PageCount = 120;
console.log(count + 1);Enable JavaScript to edit and type-check this example.
Check your prediction
121Acceptance cases before you code
Before you code, predict for each case whether it compiles and what it prints.
| Case to try | What your result should demonstrate |
|---|---|
pairs(books, "title", "pages"), then title.toUpperCase() and total += pages | Both compile; titles come out in input order; a zero page count is kept |
pairs(books, "pages", "title") | Each pair's first position is now a number and its second a string |
pairs(books, "title", "author") | Rejected at the call |
An empty Book[] | Returns an empty list |
Try deleting your function's return type annotation. The map callback's array literal is then inferred as (string | number)[], not a pair, and the first case's total += pages stops compiling. A tuple has to be asked for: the same point the tuples lesson made with as const, met from the other side.
Your turn
Checkpoint: Typed Pluck: practice
Implement pairs. For books A (10 pages), B (0 pages) and C (20 pages), print one TITLE: pages line per book with the title uppercased, then the page total 30, then the length of the pairs from an empty book list.
// Design the signature first, then a one-line body, then the tests.Enable JavaScript to edit and type-check this example.
Hint 1: the idea
There are two keys and each can be any key of the record type, so each needs its own type parameter. The type of the property at a key K is T[K].
Hint 2: a first step
Write the return type first: a list of two-position tuples whose positions use the two indexed access types. Then let map build each pair from the record.
Show one solution
function pairs<T, L extends keyof T, V extends keyof T>(
records: readonly T[],
labelKey: L,
valueKey: V
): [T[L], T[V]][] {
return records.map(record => [record[labelKey], record[valueKey]]);
}
type Book = { title: string; pages: number };
const books: Book[] = [
{ title: "A", pages: 10 },
{ title: "B", pages: 0 },
{ title: "C", pages: 20 }
];
let total = 0;
for (const [title, pages] of pairs(books, "title", "pages")) {
console.log(`${title.toUpperCase()}: ${pages}`);
total += pages;
}
console.log(total);
const noBooks: Book[] = [];
console.log(pairs(noBooks, "title", "pages").length);Enable JavaScript to edit and type-check this example.
A: 10
B: 0
C: 20
30
0L and V are separate because the two keys are chosen independently; each is constrained by keyof T, which is what rejects "author" (TS2345). The return type [T[L], T[V]][] does two jobs: it tells callers each position's exact type, and it gives map's callback a contextual type, so the array literal is checked as a tuple instead of being widened to (string | number)[]. The checker cannot see whether you put the label first or kept input order; the A/B/C lines and the 30 are the evidence for that.
Change it and test it
Call pairs with a key variable typed keyof Book and read the resulting pair type. Explain why it is a union, and why that is the honest answer. Then make the parameter records: T[] instead of readonly and check whether a readonly Book[] can still be passed.
Completion is saved in this browser only. It does not measure mastery.