TypeScript · Types that pay for themselves
What does keyof do?
Short answer
keyof T produces a union of the property names of T. It is the basis for type-safe property access, mapped types and generic helpers that accept only real keys.
keyof is a type operator. Applied to an object type, it yields the union of its keys. Applied to a type with an index signature, it yields the index type, such as string or number. It is commonly used with generics to connect a key argument to the resulting property type.
type User = { id: number; name: string };
type UserKey = keyof User;
function get<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Asha" };
const name = get(user, "name");What keyof includes
- Own property names of an object type
- Index signature keys, such as string for Record<string, number>
- Numeric keys when the type has a numeric index signature
- Known symbol keys when they are declared with unique symbol
keyof does not include arbitrary properties that are not in the type. That is the point: it lets a helper reject a typo like "nmae" at compile time instead of returning undefined at runtime. Combined with indexed access, it keeps the key and the value type in sync.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What does keyof return for a type with an index signature?
- 2How does keyof behave on a union?
- 3How do keyof and indexed access work together?
- 4Why is keyof useful for generic helpers?
Say it in the interview
keyof T gives me the union of property names of T. I use it with generics so a helper only accepts real keys and can return the exact property type. It is also the foundation for mapped types and utility types like Pick. The important detail is that keyof respects index signatures and does not include arbitrary strings unless the type allows them.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live TypeScript mock interview and get scored feedback on depth, clarity and confidence.