Skip to the solution
MediumFrontend9 min read

What do keyof and typeof do in TypeScript?

168 views

The problem

Question presented to candidate: "What do keyof and typeof do in TypeScript? How is TypeScript's typeof different from JavaScript's, and how would you combine them with generics?"

What a strong answer should cover:

  • keyof T is a type operator: the union of T's property names (keyof User is "id" | "name" | "admin"); it arrived in TypeScript 2.1 with indexed access types
  • typeof x in a type position captures the static type of an existing value; in a value position it is JavaScript's run-time operator returning a string like "object"
  • keyof typeof obj gives the keys of a value without writing a separate type; ReturnType<typeof fn> reuses a function's result type
  • The generic pattern <T, K extends keyof T>(obj: T, key: K): T[K] for type-safe property access
  • Edge cases: index signatures (keyof { [k: string]: X } is string | number), keyof (A | B) is only the shared keys, keyof of a class omits private members, and Object.keys returns string[] on purpose
  • A type name cannot be used with value typeof (TS2693): types and values live in separate namespaces

Code / implementation expected: Yes β€” keyof typeof on a config object and a getProperty or pluck helper.

  • keyof
  • typeof

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.

TypeScriptkeyof, both kinds of typeof, and pluck
TypeScriptEdge cases: index signatures, unions, Object.keys, classes

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 61 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 are branded (nominal) types?

Continue