What does the keyof operator do in TypeScript?
keyof T produces a union of the property names of type T as string literals. For { name: string; age: number } it gives "name" | "age". It is used to restrict a value to valid keys of an object.
Explain it simply
Think of a table's column headers. keyof hands you the list of valid headers as a type, so you cannot ask for a column that does not exist.
The result is a union of literal types. A function that takes a key can then use keyof Student as the parameter type, and the compiler rejects typos like "nme" immediately.
Example
interface Student { name: string; roll: number; city: string }
type Field = keyof Student; // "name" | "roll" | "city"
function show(s: Student, field: Field) {
console.log(s[field]); // type: string | number
}
const s: Student = { name: "Asha", roll: 7, city: "Pune" };
show(s, "city");
// show(s, "nme"); // Error: not assignable to Field
// keyof on a type with an index signature
type Dict = { [key: string]: number };
type K = keyof Dict; // string | numberWhat to say in the interview
"keyof T gives the union of T's property names as literal types. I use it to make parameters accept only real keys, usually together with a generic like K extends keyof T. For a type with a string index signature keyof gives string | number, because numeric keys are converted to strings."