Skip to the solution
MediumFrontend9 min read

What is an index signature?

319 views

The problem

Question presented to candidate: "Say you count words in a text and store the counts in an object whose keys you cannot know in advance. How do you type that object, and what are the gotchas?"

What a strong answer should cover:

  • Syntax and meaning: { [key: string]: number } says every string key maps to a number; key types can be string, number, symbol, template literal patterns such as `data-${string}` (4.4+) or unions of these
  • Rules: named properties must fit the index signature type (TS2411), and a number index type must be assignable to the string one (TS2413), because number keys become strings at run time
  • The big gotcha: reading a missing key is typed number, not number | undefined, unless noUncheckedIndexedAccess is on (not part of strict)
  • Run-time traps of plain objects as dictionaries: inherited keys such as constructor and the __proto__ setter; Object.create(null) or Map avoid them
  • When to use Record<K, V> (same thing for string keys, required keys for literal unions) and when a Map is the better tool

Clarifying questions expected:

  • Is the set of keys truly open, or a known list (which would call for Record<Union, V>)?
  • Can keys come from user input (which raises the __proto__ issue)?

Code / implementation expected: Yes β€” a typed word-count dictionary and a lookup that handles missing keys.

  • index-signature

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptThe rules of index signatures, checked by tsc
TypeScriptPlain object vs Object.create(null) vs Map as a dictionary

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 52 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What is type widening and how do you prevent it?

Continue