The keyof Operator
Extracting the keys of an object into a literal union type.
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.
id: number;
name: string;
}
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
keyofextracts 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.