AI Hints
Home›TypeScript Tutorial›Combining Shapes
TypeScript · Lesson 27 of 120

Index Signatures

Dictionaries.

⏱ 2 min read▶ Video at 21:16🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Sometimes you don't know the property names in advance. Like stock counts by store, where stores can be added any time. An index signature says any string key maps to a certain type.

Index Signatures
From the video: Index Signatures
  • Unknown keys
  • Stock by store
  • Index signature

Stock by store

Stock maps any string key to a number. We can add a new store at any time. Then we loop over the entries, and add up the total. Run it.

app.tstypescript
const stock: { [store: string]: number } = {
  Leeds: 12,
  York: 5,
};

stock["Hull"] = 8;

let total = 0;
for (const [store, count] of Object.entries(stock)) {
  console.log(store, count);
  total += count;
}
console.log("Total:", total);
Output
Leeds 12
York 5
Hull 8
Total: 25

Values must match

Now we set a store's stock to text. Run it. Every value must be a number.

app.tstypescript
const stock: { [store: string]: number } = { Leeds: 12 };
stock["York"] = "five";
Output
app.ts line 2: Type 'string' is not assignable to type 'number'.

Summary

Index signatures describe dictionaries, with any keys and one value type. Next, practice with a shopping cart.

Key takeaways
  • [key: string]: number
  • Any keys
  • One value type
Next up: Practice: A Shopping Cart — objects together