Yuzhe's Blog

yuzhes

3312 · Parameters

Posted at # TypeScript # TypeChallenge # TC-Easy
EN ·

3312 · Parameters

Challenge Link

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 : never

Explanation

We use infer inside a conditional type to capture the parameter list of function type T.

Step by step:

  1. T extends (...args: any[]) => any — constrains T to any function type
  2. T extends (...args: infer P) => any — tries to match T as a function; if it matches, infer P captures the rest parameter tuple
  3. ? P : never — if matched, return P (the parameter types as a tuple); otherwise never

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: