TypeScript Course
TypeScript
/
Advanced

keyof Operator

Definition

The `keyof` operator takes an object type and produces a string or numeric literal union of its keys.

Explain Like I'm New

Imagine having a massive object with 50 properties. If you want a type that represents 'Any of the keys inside this object', you don't want to type out `'name' | 'age' | 'email' | ...` manually. The `keyof` operator reaches into the object and auto-generates that union for you.

Real World Example

Writing a generic `getProperty(obj, key)` function. You use `keyof` to ensure the developer can only pass a string that ACTUALLY exists as a key on that specific object.

Common Use Cases

  • •Dynamic property access
  • •Creating highly strict utility functions

Interactive Example

Loading Code Playground...

Interview Questions

basic

  • What does `keyof User` return if User has `{ id: 1, name: 'A' }`?

intermediate

  • How do you use `keyof` in combination with Generics?

advanced

  • What does `keyof` return for an Array type?

Flash Cards

Question

What does it return?

Click to reveal answer
Answer

It returns a union of string literals: `'id' | 'name'`.

Question

What does it return for an Array?

Click to reveal answer
Answer

Because arrays are objects in JS, `keyof any[]` returns a union of all array method names AND indexes: `'length' | 'push' | 'pop' | 'map' | ... | number`.