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> to extract element types from arrays
  2. Create PromiseResult<T> to extract resolved types from Promises
  3. Create FunctionReturn<T> to extract return types from functions

Please set the playground first

Loading "Introduction to infer"
Loading "Introduction to infer"