Introduction to infer

Infer
πŸ‘¨β€πŸ’Ό The infer keyword is one of TypeScript's most powerful features. It lets you extract types from within other types.
Think of infer as declaring a type variable that TypeScript fills in by pattern matching:
// "If T has a payload property, call that payload P"
type PayloadType<T> = T extends { payload: infer P } ? P : never

type A = PayloadType<{ payload: 'ping' }> // 'ping'
type B = PayloadType<{ payload: 42 }> // 42
type C = PayloadType<string> // never - no payload to infer
The pattern is always:
T extends SomePattern<infer X> ? X : Fallback
Where infer X captures the type at that position.
🐨 Open
index.ts
and:
  1. Create ArrayElement<T> β€” element type for arrays, otherwise never
  2. Create PromiseResult<T> β€” resolved type for Promises, otherwise T
  3. Create FunctionReturn<T> β€” return type for functions, otherwise never
  4. Add a runtime fetchUser that resolves to { id: '1', name: 'Alice' } and is typed as Promise<{ id: string; name: string }>
  5. Create FetchUserResult by deriving it from fetchUser's result type with PromiseResult (so it resolves to the user object shape, not a Promise)
  6. Export fetchUser
Completion check: await fetchUser() returns { id: '1', name: 'Alice' }.

Please set the playground first

Loading "Introduction to infer"
Loading "Introduction to infer"
Login to get access to the exclusive discord channel.
Loading Discord Posts