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>β element type for arrays, otherwisenever - Create
PromiseResult<T>β resolved type for Promises, otherwiseT - Create
FunctionReturn<T>β return type for functions, otherwisenever - Add a runtime
fetchUserthat resolves to{ id: '1', name: 'Alice' }and is typed asPromise<{ id: string; name: string }> - Create
FetchUserResultby deriving it fromfetchUser's result type withPromiseResult(so it resolves to the user object shape, not a Promise) - Export
fetchUser
Completion check:
await fetchUser() returns
{ id: '1', name: 'Alice' }.

