3312 · Parameters
Less than 1 minuteTC-Easy
3312 · Parameters
Problem
Implement the built-in Parameters<T> generic without using it.
const foo = (arg1: string, arg2: number): void => {}
type FunctionParamsType = MyParameters<typeof foo> // [string, number]Solution
type MyParameters<T extends (...args: any[]) => any> =
T extends (...args: infer P) => any ? P : neverExplanation
We use infer inside a conditional type to capture the parameter list of function type T.
Step by step:
T extends (...args: any[]) => any— constrainsTto any function typeT extends (...args: infer P) => any— tries to matchTas a function; if it matches,infer Pcaptures the rest parameter tuple? P : never— if matched, returnP(the parameter types as a tuple); otherwisenever
The key insight is that ...args always captures parameters as a tuple, so infer P gives us exactly the tuple of parameter types.
Key concepts:
inferkeyword — captures a type within a conditional type pattern- This is exactly how the built-in
Parameters<T>utility is implemented in TypeScript's lib
