Course contentsShow
← TypeScript
Lesson 638 of 1,79615. Generic ConstraintsFree lesson

keyof and Mapped Types Together

Using keyof inside mapped types to iterate over keys: [K in keyof T] for transformations.

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 T produces "name" | "age"
  • K in iterates over each literal: first K = "name", then K = "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.