Async return type

2 snippets in TypeScript

TSTypeScript

Return Type Annotations

TS · Type Annotations
Syntax
function fn(): ReturnType { ... }
const fn = (): ReturnType => { ... };
Example
function findUser(id: string): User | undefined {
  return userDatabase.get(id);
}

// Arrow function return type
const formatCurrency = (amount: number): string => {
  return `$${amount.toFixed(2)}`;
};

// Async function
async function fetchOrder(id: string): Promise<Order> {
  const resp = await fetch(`/api/orders/${id}`);
  return resp.json();
}
Output
// Async functions always return Promise<T>

Note Explicit return types are especially valuable for public API functions, async functions, and functions with multiple return paths. They also speed up type-checking in large projects since the compiler does not need to analyze the function body.

Awaited<T>

TS · Utility Types
Syntax
type Result = Awaited<PromiseType>;
Example
type PromisedUser = Promise<{ id: string; name: string }>;
type ResolvedUser = Awaited<PromisedUser>;
// { id: string; name: string }

// Handles nested promises
type DeepPromise = Promise<Promise<Promise<number>>>;
type DeepResolved = Awaited<DeepPromise>;
// number

// Practical: extract resolved type from async function
async function loadConfig() {
  return { apiUrl: "https://api.example.com", timeout: 5000 };
}
type Config = Awaited<ReturnType<typeof loadConfig>>;
Output
// Awaited recursively unwraps all layers of Promise

Note Added in TS 4.5. Awaited recursively unwraps nested Promises until it hits a non-Promise type. Before Awaited existed, developers had to write custom recursive unwrap types. Works with any thenable, not just native Promises.

Frequently asked questions

How does TypeScript handle async return type?
TypeScript covers this with 2 copy-ready snippets on this page. The "Return Type Annotations" snippet in TypeScript uses `function fn(): ReturnType { ... }`.
Which code does the TypeScript example use?
The "Return Type Annotations" snippet uses `function fn(): ReturnType { ... }`, from the Type Annotations section of the TypeScript cheat sheet.
What other TypeScript snippets are shown for "async return type"?
Besides "Return Type Annotations", this page also shows "Awaited<T>".
Is there anything to watch out for?
Yes. For "Return Type Annotations": Explicit return types are especially valuable for public API functions, async functions, and functions with multiple return paths. They also speed up type-checking in large projects since the compiler does not need to analyze the function body.