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
Tis a promise (Promise<U>), thenAwaited<T>returns typeU. - If
Tis not a promise, thenAwaited<T>returnsTitself.
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
fetchDatareturnsPromise<number>. ReturnType<typeof fetchData>extracts function's return type, i.e.Promise<number>.Awaited<Promise<number>>unwraps promise, returning typenumber.
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?
-
Simplifying work with async functions
Awaited allows explicitly specifying result type obtained after awaiting promise, simplifying typing and reducing duplication. -
Recursive type extraction
When working with nested promises, Awaited automatically "unwraps" nested types, returning final value. -
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
Tis not a promise, Awaited simply returnsTunchanged. - 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.