Skip to the solution
MediumFrontend10 min read

What are indexed access types?

759 views

The problem

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 property K on type T, using element-access syntax at the type level (added with keyof in 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), number for 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 needs typeof
  • The generic pattern K extends keyof T with return type T[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>.

  • index-access

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

10 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 forms of T[K] and a generic getter
TypeScriptEdge cases: optional keys, index signatures, unions and a typed setter

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 35 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

How does the 'in' operator narrow types?

Continue