Advanced Types
keyof & typeof Operators
Master the keyof index type query operator and typeof type query operator in TypeScript, extracting keys from objects and types from runtime values.
TypeScript features two fundamental type query operators: keyof (returns a union of object property keys) and typeof (extracts the static type from a runtime value).
1. The keyof Operator
The keyof operator takes an object type and produces a string or numeric literal union of its keys.
2. The Type-Level typeof Operator
In JavaScript, typeof evaluates runtime type strings ("string", "object"). In TypeScript, typeof used in a type position extracts the static TypeScript type of a runtime variable, function, or object literal.
3. Combining keyof typeof (Extract Keys from Runtime Objects)
Combining keyof and typeof allows you to extract property key unions directly from runtime objects without duplicating type definitions:
4. Interactive Code Playground
Test keyof and typeof operators below:
5. Summary Table
| Operator | Usage Context | Input | Output |
|---|---|---|---|
keyof | Type Context | Object Type | Union of property key strings/numbers |
typeof | Type Context | Runtime Variable / Function | Static TypeScript Type definition |
keyof typeof | Type Context | Runtime Object Variable | Union of runtime object property keys |