TypeScript Generic Function Exercises
Practise preserving a key-to-value relationship without using any. Predict the inferred result of each call before running the worked solution.
Your brief
Write a helper that reads a property only when the key exists in the declared object type. It should preserve a numeric result for packets and a textual result for code. Then try an unsupported key in your local compiler and explain why it must fail. The goal is to connect type parameters to a useful contract, not memorize a long generic signature without understanding it.
Run the code
Try in playground loads this source without running it. Choose Run when ready. The existing TypeScript 5.8.3 worker transpiles and executes one file; it does not perform full semantic type checking, load npm imports or provide DOM/Node APIs. Use the local compiler for the type contract.
For a full check, save the three downloads together in a new folder, run npm install, then npm run check. Use npm run build followed by npm start to execute the checked JavaScript with Node. The supplied project enables strict checking, indexed-access checks and exact optional properties.
Example
Show the worked solution
function selectField<T, K extends keyof T>(row: T, key: K): T[K] { return row[key]; }
const lot = { code: "EX-4", packets: 6 };
const code = selectField(lot, "code");
const packets = selectField(lot, "packets");
console.log(code.toLowerCase(), packets * 2);
Expected result
ex-4 12
T captures the row shape and K captures the particular permitted key. T[K] carries that choice into the result. A return type such as string | number would lose useful information for each call; any would discard checks altogether. The worked answer is hidden until requested so you can attempt the signature first.
Try a change
Extend the exercise to select two keys into a tuple. Explain how your return type preserves the type at each position.