Utility Type Parameters in TypeScript
Parameters is a utility type in TypeScript that allows finding out what parameter types a function has. It turns a function's argument list into a tuple and helps avoid code duplication.
Syntax
Parameters<T>
T— function type whose parameters you want to extract.- Result — array (tuple) with types of all parameters.
Usage Example
Example 1. Extracting function parameter types
function add(a: number, b: number): number {
return a + b;
}
type AddParameters = Parameters<typeof add>;
// AddParameters has type: [number, number]
In this example:
- Function
addtakes two parameters of typenumber. Parameters<typeof add>extracts types of these parameters as tuple[number, number].
Example 2. Using extracted types in another function
function multiply(a: number, b: number): number {
return a * b;
}
function processOperation(...args: Parameters<typeof multiply>): number {
// Here args has type [number, number]
return multiply(...args);
}
const result = processOperation(2, 3); // Result: 6
- Function
processOperationuses...argswith type[number, number]extracted frommultiplyfunction. - This ensures type consistency and reduces code duplication.
Why use Parameters?
- Type reuse: Avoids need to manually declare parameter types, especially useful for functions with many arguments.
- Consistency support: If function signature changes, types extracted via
Parameterswill automatically update. - Convenience for wrappers: Allows creating wrappers around functions while maintaining exact correspondence of input parameter types.
Limitations
- Overload functions: If function has multiple overloads,
Parameterswill take types from the very first signature, which may not always match expectations. - Generic functions: When working with generic functions, additional type specification may be required for correct parameter extraction.
Summary
Parameters is a powerful utility type allowing extraction of function parameter types as a tuple. This promotes stricter typing, reduces duplication and improves code maintainability, especially when functions are used in various wrappers and utilities.