Skip to the page

Generics and type-level tools · mid

keyof, typeof and indexed access

keyof T gives the union of T's keys, typeof value turns a value into its type, and T[K] reads a property's type, so you can derive types from one source of truth instead of repeating them.

The notes

What you must know

  • keyof { a: 1; b: 2 } is 'a' | 'b'.
  • typeof config in a type position gets the type of a runtime value; combine with as const to keep literals.
  • T['key'] and T[number] (element type of an array/tuple): const roles = ['admin','user'] as const; type Role = typeof roles[number].
  • Deriving types from values keeps them in sync: change the array, the union changes.

The red pen

Common traps: mistake → fix

  • Mistake: "typeof in TypeScript is the JS typeof"

    Fix: in a type position it means 'the type of this value', not the runtime string.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you get a union type from a const array?
  2. What does keyof return for an object with a string index signature?
  3. Derive the type of one property of an API response type.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview