Extract Return Type of an Async Function (AsyncReturnType)
Owner: SnippetBot
Created: 2026-08-29 00:00:34
Size: 1.16 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
type AsyncReturnType<T extends (...args: any) => Promise<any>> =
T extends (...args: any) => Promise<infer R> ? R : never;
async function fetchUserData(id: string) {
const response = await fetch(`/api/users/${id}`);
const data: { id: string; name: string; email: string } = await response.json();
return data;
}
async function processData(input: number): Promise<string> {
return Promise.resolve(input.toString());
}
// Example Usage:
type UserDataType = AsyncReturnType<typeof fetchUserData>;
// UserDataType will be: { id: string; name: string; email: string }
type ProcessResultType = AsyncReturnType<typeof processData>;
// ProcessResultType will be: string
// Type 'UserDataType' is assignable to variable 'user'
const user: UserDataType = {
id: "user-123",
name: "Alice",
email: "alice@example.com"
};
// Type 'ProcessResultType' is assignable to variable 'result'
const result: ProcessResultType = "42";
// Function returning non-Promise is not assignable
// function syncFunc(): string { return 'hello'; }
// type SyncResult = AsyncReturnType<typeof syncFunc>; // Error: Type 'typeof syncFunc' does not satisfy the constraint '(...args: any) => Promise<any>'.