What does keyof typeof do, and why is it used with objects?
typeof obj gives the type of the object and keyof turns its keys into a union, so keyof typeof obj is the union of the object's key names. It lets one object be the single source for both runtime values and key types.
Explain it simply
You keep a price list as an object. You also want a type that accepts only the item names in that list. Writing the names twice invites mistakes.
keyof typeof prices reads the names from the object itself. Add an item to the object, and the type updates. Read right to left: first typeof prices (the type), then keyof (its keys).
Example
const prices = {
chai: 10,
samosa: 15,
vadapav: 20,
};
type Item = keyof typeof prices; // "chai" | "samosa" | "vadapav"
function cost(item: Item, qty: number): number {
return prices[item] * qty;
}
console.log(cost("samosa", 4)); // Output: 60
// cost("pizza", 1); // Error
// Value types, when combined with as const
const status = { ok: 200, notFound: 404 } as const;
type Code = (typeof status)[keyof typeof status]; // 200 | 404What to say in the interview
"keyof typeof obj gives me the union of an object's keys without declaring them twice. With as const on the object, (typeof obj)[keyof typeof obj] gives the union of its values. It is a common alternative to enums."
Common mistakes
- Writing keyof obj without typeof; keyof needs a type, and obj is a value.