Course contentsShow
← TypeScript
Lesson 485 of 1,79611. Literal TypesFree lesson

Mapping Over Literal Unions

Use mapped types to derive related object shapes from a literal union, ensuring consistency across types.

Mapping Over Literal Unions

What you'll learn: How to use mapped types to transform a literal union into a consistent object shape, ensuring type safety across related structures.


The Core Idea

Imagine you have a union of string literals like "create" | "read" | "update" | "delete". You want to create an object type where each of these strings becomes a key, with a consistent value type. Instead of manually writing out every property, you can map over the union to generate the shape automatically.

This technique combines literal unions with TypeScript's mapped type syntax to create objects that stay synchronized with your union definition.

Basic Syntax

type Action = "create" | "read" | "update" | "delete";

type Permissions = {
  [K in Action]: boolean;
};

// Result:
// {
//   create: boolean;
//   read: boolean;
//   update: boolean;
//   delete: boolean;
// }

The [K in Action] syntax iterates over each member of the Action union, creating a property for each literal.

Why This Matters

Without mapping, you'd write properties manually—and if you add "list" to your Action union, you'd have to remember to update Permissions too. Mapped types keep everything in sync automatically.

type Status = "pending" | "approved" | "rejected";

type StatusHandlers = {
  [S in Status]: (data: string) => void;
};

// Each status automatically gets a handler function type

Key Takeaway: Mapped types let you derive object shapes from literal unions automatically, ensuring consistency and reducing duplication when types evolve together.