typescript / intermediate
Snippet
Extracting Function Return Types Using Conditional Types and Infer
Conditional types allow type transformations based on shape checks (T extends U ? X : Y). The 'infer' keyword introduces a type variable inside the conditional check to capture inner types, such as unwrapping a Promise returned by a function signature automatically.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
type ExtractPromiseResult<T> = T extends (...args: any[]) => Promise<infer R>? R: T extends (...args: any[]) => infer R? R: T;async function fetchUserStatus(userId: string) {return { id: userId, isActive: true, role: "admin" as const };}type UserStatus = ExtractPromiseResult<typeof fetchUserStatus>;
Breakdown
1
type ExtractPromiseResult<T> = T extends (...args: any[]) => Promise<infer R>
Checks if T is a function returning a Promise and infers the unwrapped inner resolved type R.
2
: T extends (...args: any[]) => infer R
Fallback branch that extracts return type R if T is a standard non-async function.
3
type UserStatus = ExtractPromiseResult<typeof fetchUserStatus>;
Resolves to { id: string; isActive: boolean; role: 'admin' } by extracting the resolved value of fetchUserStatus.