TypeScript `keyof` Operator
TypeScript keyof: Type-Safe Dynamic Property Lookups
The keyof operator extracts a union of all public property keys from an object type. For an interface Product with sku, title, and price, keyof Product produces "sku" | "title" | "price".
Pairing keyof with generics (<T, K extends keyof T>) lets you build dynamic getters, sorters, and form binders where misspelled field names fail immediately at compile time.
Combining keyof with Indexed Access (T[K])
Indexed access T[K] looks up the exact value type stored at key K, preserving whether a field is string, number, or boolean.
interface Product {
sku: string;
title: string;
price: number;
}
function pluckField<T, K extends keyof T>(items: readonly T[], key: K): T[K][] {
return items.map((item) => item[key]);
}
const catalog: Product[] = [
{ sku: "KB-01", title: "Keyboard", price: 85 },
{ sku: "MS-02", title: "Mouse", price: 40 },
];
const prices = pluckField(catalog, "price"); // Inferred as number[]
console.log(prices);
keyof typeof on Value Objects
keyof works only on types, not runtime JavaScript objects. To extract keys from a runtime object like const config = { host: "localhost", port: 5432 }, write keyof typeof config.
flowchart LR
A["const cfg = { host, port }"] -->|"typeof cfg"| B["{ host: string; port: number }"]
B -->|"keyof ..."| C["'host' | 'port'"]
Common Mistakes to Avoid
- Writing
keyof myObjecton a variable instead of a type:myObjectis a runtime value; always writekeyof typeof myObject. - Ignoring
number | symbolinkeyofkeys: If an interface has a string index signature{ [k: string]: unknown },keyofevaluates tostring | numberbecause JavaScript coerces numeric keys (obj[0]) to"0". - Using
Object.keys(obj)expecting(keyof T)[]:Object.keys()intentionally returnsstring[]because objects at runtime may carry extra keys beyond static types.
Frequently Asked Questions
What does keyof any evaluate to?
keyof any equals string | number | symbol, representing every valid JavaScript object property key type.
How do I restrict keys to only string keys in keyof T?
Use Extract<keyof T, string> (or keyof T & string) when passing keys to template literals or string-only functions.
Why does Object.keys(obj) not return (keyof typeof obj)[]?
Because TypeScript uses structural typing, an object variable can legally hold additional runtime properties not listed on its interface.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.