TypeScript for real code · Chapter 13 of 36
Lookups
By the end of this chapter you can type an object whose keys are data, not names you write in the code, and handle the key that is not there. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Modelling Tapri
- 5 tasks
- TypeScript
- In the all labs plan
The first 2 chapters of TypeScript for real code are free. This one comes with the all labs plan.
Why you need this
Ravi wants his stock notebook in the app: milk, tea leaves, sugar, kulhads, and whatever new thing he buys next week. Meera is adding a large chai at ₹50, and every size must have a price. The app looks up menu items by id all through the rush, and Ravi wants to know how many times each item was ordered.
All four are lookup tables. The object types you know so far list their property names, and Ravi's item names are not known when the code is written. Bunty typed the notebook object, and then no key at all can be read:
const notebook: object = { milk: 4, 'tea leaves': 2 };
console.log(notebook.milk);
$ typecheck demo.ts
demo.ts:2:22 - error TS2339: Property 'milk' does not exist on type 'object'.
His next idea was any, which lets every typo and every wrong value through.
What you build: 5 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
restock: Ravi's stock under any item name
Ravi's stock maps any item name to how many he has, like { milk: 4, 'tea leaves': 2 }. Write Stock as an index signature instead of object, so looking up any item name gives a number, and { milk: 'lots' } is a type error.
restock(stock, item, qty) returns a new table with qty added to that item; an item not in the table starts at 0. restock({ milk: 4 }, 'milk', 2) is { milk: 6 } and restock({ milk: 4 }, 'sugar', 3) is { milk: 4, sugar: 3 }. It must not change the table it was given. Keep its parameters and its return type Stock (so a quantity written as text, '2', is a type error).
- Task 2
SIZE_PRICES: a price for every size, and no others
Every size of chai needs a price, and only real sizes may have one. Type SIZE_PRICES as Record<Size, number> instead of the loose index signature, so a price list without large is a type error, and so is reading SIZE_PRICES.jumbo.
Then add the missing size that typecheck points out: a large chai is ₹50. SIZE_PRICES is { cutting: 25, regular: 40, large: 50 }.
- Task 3
menuById: the menu as a lookup by id
menuById(items) puts each menu item under its own id: menuById([chai, bun]) is { m1: chai, m2: bun }, where chai has id 'm1' and bun has id 'm2', and menuById([]) is {}.
Its return type is Record<string, MenuItem>, so looking up any id in the result gives a MenuItem, not any.
- Task 4 · interview question
Interview: priceOf, admit that an id might be missing
priceOf(byId, id) gives the price of the item with that id: with { m1: chai, m2: bun }, priceOf(byId, 'm2') is 30, and priceOf(byId, 'm9') is undefined instead of a crash.
Its return type must be exactly number | undefined, written on the function: byId[id] claims to be a MenuItem every time, so TypeScript will not add undefined by itself. Keep the parameters as they are. Dev will ask whether byId[id] is always a MenuItem, as its type says.
- Task 5
countOrders: order counts in a typed Map
countOrders(names) counts how many times each item was ordered, in a Map: for ['masala chai', 'bun maska', 'masala chai'], get('masala chai') is 2 and get('bun maska') is 1. For an empty list, the Map's size is 0.
Its return type must be exactly Map<string, number>, not Map<any, any>. An item seen for the first time has no count yet, so it starts from 0.
What you will learn
- Index signatures: one line that types every key of an object at once.
- Record: Record<K, V>, the same idea, and strict when the keys are a union: every key, and no others.
- The missing key: why table[key] claims to find something every time, and how to be honest about it.
- Map: a lookup with get and set, which admits a missing key.
More in Modelling Tapri
Build "Lookups" yourself
Tapri’s codebase grows, and types keep it honest. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of TypeScript for real code are free. This one comes with the all labs plan.