Course contentsShow
← TypeScript
Lesson 1447 of 1,79633. Inference Inversion PatternsFree lesson

Building Awaited with infer

Reconstructing the built-in Awaited utility type using recursive infer patterns to unwrap Promise types.

Building Awaited with infer

You'll learn: How to reconstruct TypeScript's built-in Awaited utility type using recursive infer patterns to unwrap nested Promise types.

The Problem Awaited Solves

When working with Promises in TypeScript, you often need to extract the type that a Promise resolves to. But promises can be nested — a Promise<Promise<string>> should ultimately resolve to string. The Awaited<T> utility unwraps these layers recursively.

Building Your Own Awaited

Here's how TypeScript implements Awaited using conditional types with infer:

type MyAwaited<T> = 
  T extends Promise<infer U> 
    ? MyAwaited<U>  // Recursively unwrap
    : T;            // Base case: not a Promise

How it works:

  1. Pattern match against Promise<infer U> — if T is a Promise, capture what it wraps in U
  2. Recurse by calling MyAwaited<U> — handles nested promises
  3. Base case — when T isn't a Promise, return it as-is

Testing the Pattern

type Test1 = MyAwaited<Promise<string>>;
// Result: string

type Test2 = MyAwaited<Promise<Promise<number>>>;
// Result: number

type Test3 = MyAwaited<Promise<Promise<Promise<boolean>>>>;
// Result: boolean

type Test4 = MyAwaited<string>;
// Result: string (not a Promise, returns as-is)

Think of it like unwrapping nested gift boxes: you keep opening boxes until you find the actual gift inside, no matter how many layers there are.

Key Takeaway: The infer keyword combined with conditional type recursion lets you extract types from wrapped structures like Promises, peeling away layers until you reach the core value type.