keyof: Type-Safe Dynamic Property LookupsThe 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.
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 Objectskeyof 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'"]
keyof myObject on a variable instead of a type: myObject is a runtime value; always write keyof typeof myObject.number | symbol in keyof keys: If an interface has a string index signature { [k: string]: unknown }, keyof evaluates to string | number because JavaScript coerces numeric keys (obj[0]) to "0".Object.keys(obj) expecting (keyof T)[]: Object.keys() intentionally returns string[] because objects at runtime may carry extra keys beyond static types.keyof any evaluate to?keyof any equals string | number | symbol, representing every valid JavaScript object property key type.
keyof T?Use Extract<keyof T, string> (or keyof T & string) when passing keys to template literals or string-only functions.
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.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.