×

typescript · level 2 · unit 4 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.