Combining typeof and keyof
Derive precise types by chaining type operators.
The Power Combo
Individually, typeof derives a type from a value and keyof lists a type's keys. Together — keyof typeof value — they produce a union of a value's actual keys, enabling fully type-safe access.
keyof typeof in Action
Start with a const object, capture its type with typeof, then list its keys with keyof. The result is a union of the object's literal key names.
const colors = { red: "#f00", green: "#0f0" }
type ColorKey = keyof typeof colors // "red" | "green"
const k: ColorKey = "red"
console.log(colors[k])All lessons in this course
- The typeof Type Operator
- The keyof Type Operator
- Indexed Access Types
- Combining typeof and keyof