Hone logo
Hone
Problems

TypeScript Parameters Helper

You're tasked with creating a utility function in TypeScript that can extract the parameter types from a given function. This is incredibly useful for creating higher-order functions, decorators, or advanced type utilities that need to inspect and manipulate function signatures. Your goal is to build a type that accurately reflects the types of arguments a function expects.

Problem Description

Implement a TypeScript utility type called ParametersHelper<T>. This type should accept a function type T as its generic argument and return a tuple type representing the types of the parameters of that function.

Key Requirements:

  • The utility type must correctly handle functions with zero, one, or multiple parameters.
  • It should accurately reflect the types of each parameter in the resulting tuple.
  • It should work with various function signatures, including optional parameters and rest parameters.

Expected Behavior:

If T is a function type, ParametersHelper<T> should yield a tuple where each element corresponds to the type of a parameter in T's signature. If T is not a function type, the behavior can be to return never or an empty tuple, though focusing on valid function types is the primary goal.

Edge Cases to Consider:

  • Functions with no parameters.
  • Functions with optional parameters (e.g., (a: number, b?: string)).
  • Functions with rest parameters (e.g., (...args: number[])).
  • Arrow functions and traditional function declarations.

Examples

Example 1:

type MyFunc1 = (a: number, b: string) => void;
type Params1 = ParametersHelper<MyFunc1>; // Expected: [number, string]

Example 2:

type MyFunc2 = (x: boolean) => number;
type Params2 = ParametersHelper<MyFunc2>; // Expected: [boolean]

Example 3:

type MyFunc3 = () => void;
type Params3 = ParametersHelper<MyFunc3>; // Expected: []

Example 4:

type MyFunc4 = (a: number, b?: string, ...rest: boolean[]) => void;
type Params4 = ParametersHelper<MyFunc4>; // Expected: [number, string | undefined, ...boolean[]]

Example 5:

type NotAFunction = number;
type Params5 = ParametersHelper<NotAFunction>; // Expected: never (or [])

Constraints

  • The solution must be implemented using TypeScript's advanced type system.
  • The solution should be a utility type, not a runtime function.
  • The type should correctly infer parameter types for standard JavaScript function signatures.

Notes

TypeScript already provides a built-in utility type called Parameters<T> that does exactly this. Your challenge is to re-implement this functionality from scratch to deepen your understanding of conditional types, infer keyword, and tuple manipulation in TypeScript. Think about how you can use conditional types to check if the input T is a function and how to extract its arguments. The infer keyword will be crucial here.

Loading editor...
typescript