typescript · level 2 · unit 4 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is a lookup table from keys to values.
A price list matches each snack's name to its price. A Record type describes that: Record<string, number> means every is a string and every value a number. The two types go inside angle brackets, < and >.
Look a value up with its key in square brackets: prices["cake"]. Put a value at a new key to add it. Object.keys(prices) gives you every key in an array, ready for a loop.
Use a literal union for the keys, like Record<Size, number>, and the checker insists on a value for every size.
const prices: Record<string, number> = { tea: 1.5, cake: 2.8 };
prices["toast"] = 1.2;
console.log(prices["cake"]);
for (const item of Object.keys(prices)) {
console.log(`${item}: £${prices[item]}`);
}
type Size = "small" | "large";
const cups: Record<Size, number> = { small: 250, large: 400 };
console.log(cups.large); A key that was never added gives undefined, and the checker cannot spot that, so add keys before you read them.
guess first
Counting votes with a Record. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const votes: Record<string, number> = {};
const picks: string[] = ["pizza", "tacos", "pizza", "pizza"];
for (const pick of picks) {
votes[pick] = (votes[pick] ?? 0) + 1;
}
console.log(votes);
your turn
Your turn. Grow a phrasebook.
Add an English word of your own and its French meaning as a new key and value. The loop then shows every pair.
fix it
One size has no price. Fix it!
- Read the error:
TS2741: Property 'medium' is missing. The object on line 2 has a gap. Record<Size, number>needs a price for every size on line 1. Which one is missing?- Add
medium: 3,to the object on line 2, then press run.
nailed it
you can look things up by key. :D
Record<Key, Value>describes a lookup table.- Read and add values with a key in square brackets.
Object.keysgives every key, ready to loop over.
new words in your collection
- Record
- key
This lesson isn’t saved. A free account remembers every lesson you finish.