Question presented to candidate:
"TypeScript lets you write Person["name"] in a type. What is that, what can you put inside the brackets, and where would you actually use it?"
What a strong answer should cover:
- An indexed access type
T[K]looks up the type of propertyKon typeT, using element-access syntax at the type level (added withkeyofin TypeScript 2.1) - The index must be a type: a literal key, a union of keys (gives a union of property types),
keyof T(all value types),numberfor array elements, or a literal index or"length"on a tuple T[K]is checked: a key that does not exist is error TS2339, and a value used as the key needstypeof- The generic pattern
K extends keyof Twith return typeT[K], so getters and setters follow the key the caller passes - Practical use: drilling into large generated or third-party types (
Api["data"]["users"][number]) instead of re-declaring them - Edge cases: optional properties include
undefined, index signatures are indexed by their key type, a union of objects only exposes keys every member has
Code / implementation expected: Yes β derive a few types with T[K] and write a typed getProp<T, K extends keyof T>.