keyof and Property Iteration
What you'll learn: How keyof extracts property keys as a union and how mapped types use that union to iterate over properties.
The Core Mechanism
When you write keyof T, TypeScript extracts all property keys from type T as a string literal union. This union becomes the foundation for mapped types, which iterate over each key to transform the original type.
Think of it like this: keyof gives you a list of all the doors in a building, and a mapped type lets you walk through each door and change what's inside the room.
How keyof Feeds Mapped Types
type Person = {
name: string;
age: number;
};
type Keys = keyof Person; // "name" | "age"
Here, keyof Person produces the union "name" | "age". Now a mapped type can iterate over this union:
type ReadonlyPerson = {
readonly [K in keyof Person]: Person[K];
};
The [K in keyof Person] syntax means "for each key K in the union produced by keyof Person". TypeScript iterates over "name" and "age", applying readonly to each property while preserving its original type with Person[K].
The Iteration Pattern
The in keyword iterates over the union. For each literal type in the union, TypeScript creates a property. This is why mapped types can transform every property systematically — they loop through the keys that keyof provides.
Key Takeaway: keyof extracts property keys as a union type, and mapped types use [K in keyof T] to iterate over that union, transforming each property systematically.