typescript / intermediate
Snippet
Extracting Function Parameter Types with Conditional Types and the infer Keyword
TypeScript allows you to dynamically infer internal types using conditional types combined with the 'infer' keyword. This technique enables you to extract argument signatures directly from existing functions without duplicating type definitions.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
type ExtractFirstArg<T> = T extends (first: infer U, ...rest: any[]) => any ? U : never;function logUser(user: { id: number; name: string }): void {console.log(`${user.name} (${user.id})`);}type UserParam = ExtractFirstArg<typeof logUser>;const validUser: UserParam = { id: 101, name: "Alice" };logUser(validUser);
Breakdown
1
type ExtractFirstArg<T> = T extends (first: infer U, ...rest: any[]) => any ? U : never;
Defines a generic type that checks if T is a function signature and captures its first argument into type variable U.
2
type UserParam = ExtractFirstArg<typeof logUser>;
Applies ExtractFirstArg to logUser's function type to extract its first parameter type dynamically.
3
const validUser: UserParam = { id: 101, name: "Alice" };
Creates an object guaranteed to match the extracted parameter structure.