Hack Frontend Community

Utility Type Awaited in TypeScript

Awaited is a utility type in TypeScript introduced in version 4.5 that extracts the value from a Promise. If a function or variable returns Promise<T>, then Awaited<T> will give T itself.


Syntax

Awaited<T>
  • T — type that can be a promise or value.
  • If T is a promise (Promise<U>), then Awaited<T> returns type U.
  • If T is not a promise, then Awaited<T> returns T itself.

Usage Example

Example 1. Extracting value from promise

async function getData(): Promise<number> {
  return 42;
}

type DataType = Awaited<ReturnType<typeof getData>>;
// DataType → number

In this example:

  • Function fetchData returns Promise<number>.
  • ReturnType<typeof fetchData> extracts function's return type, i.e. Promise<number>.
  • Awaited<Promise<number>> unwraps promise, returning type number.

Example 2. Working with nested promises

type NestedPromise = Promise<Promise<string>>;

type Result = Awaited<NestedPromise>;
// Result → string
  • If there are multiple promises, Awaited unwraps them to final value.

Why use Awaited?

  1. Simplifying work with async functions
    Awaited allows explicitly specifying result type obtained after awaiting promise, simplifying typing and reducing duplication.

  2. Recursive type extraction
    When working with nested promises, Awaited automatically "unwraps" nested types, returning final value.

  3. Support for async utilities
    Awaited is useful when building generic utilities for async code where knowing exact data type after promise resolution is important.


Limitations

  • If type T is not a promise, Awaited simply returns T unchanged.
  • In case of complex conditional types or generic functions, more careful type description may be required for correct inference.

Summary

Awaited is a powerful utility type that allows automatically extracting value types from promises. It's especially useful for asynchronous programming in TypeScript, providing accurate typing of returned data and simplifying work with nested promises.