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 : FallbackWhere
infer X captures the type at that position.π¨ Open
and:
- Create
ArrayElement<T>to extract element types from arrays - Create
PromiseResult<T>to extract resolved types from Promises - Create
FunctionReturn<T>to extract return types from functions


