Course contentsShow
← TypeScript
Lesson 726 of 1,79617. Mapped TypesFree lesson

Mapping Over Literal Types

How mapped types work with string literal unions to create specific property sets.

Mapping Over Literal Types

What you'll learn: How mapped types work with string literal unions to create specific property sets.


When you combine mapped types with string literal unions, you get precise control over exactly which properties exist in your object type. This is where mapped types truly shine—you're not just iterating over existing keys, you're creating a type from a predefined list of allowed keys.

The Core Idea

Instead of using keyof to iterate over properties of an existing type, you can map directly over a union of literal types. TypeScript will create one property for each member of that union.

type Status = "pending" | "success" | "error";

type StatusFlags = {
  [K in Status]: boolean;
};

// Result:
// {
//   pending: boolean;
//   success: boolean;
//   error: boolean;
// }

Here, K in Status iterates over each literal value in the union ("pending", "success", "error"), and creates a property with that exact name.

Why This Matters

This pattern ensures your object type has exactly the properties you specify—no more, no less. It's perfect for configuration objects, state maps, or lookup tables where you need compile-time guarantees about which keys exist.

type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";

type MethodHandlers = {
  [M in HttpMethod]: () => void;
};

// TypeScript ensures you implement ALL four methods
const handlers: MethodHandlers = {
  GET: () => {},
  POST: () => {},
  PUT: () => {},
  DELETE: () => {}
};

Key Takeaway: Mapping over literal type unions lets you programmatically generate object types with exact, predefined property names, ensuring type safety and completeness at compile time.