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.

GroupGenerics
KindOperator
Strict modeNot 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 TThe key union: every key of T as a literal union (degrades to string | number when a string index signature exists)
K extends keyof TThe 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.
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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏