keyof The keyof Operator
Last updated: 2026-10-22
keyof The keyof Operator
keyof T collects every key of an object type T into a literal union: keyof Settings is "volume" | "theme". It is the bedrock of key-name type safety — with a generic constraint, a typo in a key argument errors immediately.
| Group | Generics |
|---|---|
| Kind | Operator |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
interface Settings {
volume: number;
theme: string;
}
type SettingKey = keyof Settings; // "volume" | "theme"
function read<T, K extends keyof T>(settings: T, key: K): T[K] {
return settings[key];
}
⚙️ Parameters
| keyof T | The key union: every key of T as a literal union (degrades to string | number when a string index signature exists) |
|---|---|
| K extends keyof T | The classic pairing: key arguments are constrained to real keys |
| T[K] | Indexed access: the value type for that key — vol is number automatically |
Returns:keyof is a type operator with no runtime code; T[K] links the return type precisely to the key.
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
60 dark
(Runtime output after transpilation; a typo like "volumn" is a compile error — K is constrained by keyof T)
💡 Notes
ℹ️ Info keyof stays in sync automatically: add a field to Settings and the union gains a member — something hand-writing "volume" | "theme" | "lang" can never do.
💡 Tip keyof plus generics is the raw material of utility types: Pick<T, K extends keyof T>, Omit and friends rely on it to allow only real keys.
⚠️ Note keyof on an array includes numeric indices and all array method names ("length" | "push" | ...); to get an array's element type use T[number], not keyof.
🏷️ Related Generics
💡 Related cases
More cases coming soon.
📚 Related tutorials
❓ FAQ
Q keyof typeof obj vs keyof SomeInterface?
A typeof obj first turns the value back into a type, then takes keys (typical for const objects); keyof Interface works on the type directly. Both yield equivalent literal unions.
Q What does keyof give on a type with an index signature?
A For { [k: string]: boolean }, keyof is string | number — keys stop narrowing to literals and typo protection disappears; avoid broad index signatures when you need exact keys.
Q What is T[K]?
A An indexed access type: look up T's value type with key type K. For K = "volume", T[K] is number — the key-to-value-type linkage is entirely this.