Course contentsShow
← TypeScript
Lesson 796 of 1,79618. Conditional TypesFree lesson

infer with Function Parameter Types

Capturing parameter types from function signatures using infer in the parameter position of extends clauses.

infer with Function Parameter Types

What you'll learn: How to use infer to extract and capture the parameter types from function signatures in conditional types.

The Core Idea

You've already seen infer extract return types from functions. Now we'll use it to capture what goes into a function instead of what comes out. This is particularly useful when you need to work with callback types, wrappers, or when building utilities that need to know what arguments a function accepts.

How It Works

Place infer P in the parameter position of a function type within an extends clause:

type GetParameters<T> = T extends (arg: infer P) => any ? P : never;

This reads as: "If T is a function that takes one argument, capture that argument's type as P and return it; otherwise, return never."

Basic Example

type GetFirstParam<T> = T extends (first: infer F) => any ? F : never;

type Fn1 = (name: string) => void;
type Param1 = GetFirstParam<Fn1>;  // string

type Fn2 = (age: number) => boolean;
type Param2 = GetFirstParam<Fn2>;  // number

Multiple Parameters

You can use multiple infer keywords to capture different parameter positions:

type GetSecondParam<T> = T extends (first: any, second: infer S) => any ? S : never;

type Handler = (id: number, data: string) => void;
type SecondArg = GetSecondParam<Handler>;  // string

Practical Use Case: Matching Callback Signatures

type ExtractCallbackArg<T> = T extends (callback: (arg: infer A) => any) => any ? A : never;

type FetchUser = (onSuccess: (user: { name: string }) => void) => void;
type UserType = ExtractCallbackArg<FetchUser>;  // { name: string }

Key Takeaway: Use infer in the parameter position of function types within extends clauses to capture and extract argument types, enabling type-level introspection of function signatures.