ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

TypeScript Tutorial• 9 min read

Conditional & Mapped Types

Building dynamic type transformers with infer and keyof mappings

Conditional types take the form T extends U ? X : Y. When combined with mapped types and the infer keyword, you can build powerful meta-programming type machinery.

Understanding Conditional and Mapped Types

Conditional types: Express logic at compile time: type IsString<T> = T extends string ? true : false;.

The infer keyword: Allows you to deduce and extract a type inside a conditional branch (e.g., unwrapping Promises: type Awaited<T> = T extends Promise<infer R> ? R : T;).

Mapped types: Iterate over keys using [K in keyof T] to transform property attributes or names dynamically.

Template literal types: Combine string unions to produce patterns: type Event = ${string}_event;.

Unwrapping Promises with Infer
// Custom type helper that unwraps Promise return values
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;

// Async fetch function signature
async function fetchMetrics() {
  return { activeUsers: 4820, latencyMs: 14.2 };
}

// Extract the resolved return type automatically
type Metrics = UnwrapPromise<ReturnType<typeof fetchMetrics>>;

const currentMetrics: Metrics = {
  activeUsers: 5100,
  latencyMs: 11.8
};

console.log(`Users: ${currentMetrics.activeUsers}`);
infer U captures the type resolved by the Promise without manual duplicate declarations.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which TypeScript keyword allows you to introduce and extract a type variable inside a conditional type check?