The keyof Operator

Extracting the keys of an object into a literal union type.

TypeScript3 min readConcept 13 of 54

Extracting object keys

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

If you have an object type with properties id and name, keyof will generate the union type 'id' | 'name'.

Dynamic but safe property access

Imagine writing a getProperty function. You want the user to pass in an object and a key, and return the value.

If you type the key as string, the user could pass 'randomKey', and TypeScript wouldn't complain. By typing the key as keyof MyObject, TypeScript will strictly enforce that they only pass valid keys.

Using keyof

typescript type User = { id: number; name: string; isActive: boolean; }; type UserKeys = keyof User; // Result: "id" | "name" | "isActive" let key: UserKeys = "name"; // OK key = "email"; // Error!

Try it

Watch how keyof extracts the property names from an interface and assembles them into a literal union type.

type User = {
id: number;
name: string;
};

// Extract keys into a union type
type UserKeys = keyof User;
User Interface
{
  id: number;
  name: string;
}
"id"
|
"name"

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1If you have a JavaScript object 'const settings = { theme: "dark" }', how do you extract its keys into a union type?

Remember this

  • keyof extracts the keys of a type into a literal union.
  • It is essential for safely typing dynamic property access.
  • To extract keys from a JS object, use keyof typeof obj.
  • It extracts keys, not values.

Done with this concept?

Mark it complete to track your progress. No login needed.