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 anumber; key types can bestring,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
numberindex type must be assignable to thestringone (TS2413), because number keys become strings at run time - The big gotcha: reading a missing key is typed
number, notnumber | undefined, unlessnoUncheckedIndexedAccessis on (not part ofstrict) - Run-time traps of plain objects as dictionaries: inherited keys such as
constructorand the__proto__setter;Object.create(null)orMapavoid them - When to use
Record<K, V>(same thing for string keys, required keys for literal unions) and when aMapis 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.