keyof and Mapped Types Together
You'll learn how to combine keyof with mapped types to iterate over every key in a type and apply transformations.
The Core Idea
We've already seen keyof extract all keys from a type as a union. We've also seen mapped types transform object types. When you combine them with the syntax [K in keyof T], you create a powerful loop over all properties of a type, letting you apply systematic transformations to every key-value pair.
Think of it like a for...in loop in JavaScript, but at the type level. You're saying: "For each key K in type T, create a new property with some transformation applied."
Basic Pattern
type T = { name: string; age: number };
// Map over all keys of T
type ReadonlyVersion<T> = {
readonly [K in keyof T]: T[K];
};
type Result = ReadonlyVersion<T>;
// Result: { readonly name: string; readonly age: number }
Here, [K in keyof T] means:
keyof Tproduces"name" | "age"K initerates over each literal: firstK = "name", thenK = "age"T[K]looks up the original type for that key
Real Transformation Example
type User = { id: number; email: string; active: boolean };
// Make all properties nullable
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
type NullableUser = Nullable<User>;
// { id: number | null; email: string | null; active: boolean | null }
You're iterating over every key and appending | null to its type.
Key Takeaway: Using [K in keyof T] lets you iterate over all keys of a type and apply transformations systematically, creating powerful generic type utilities.