Extracting Function Parameters with Parameters
What you'll learn: How to use the built-in Parameters<T> utility type to extract a tuple type representing all parameter types from any function type.
What Is Parameters<T>?
The Parameters utility type is TypeScript's way of letting you ask: "What arguments does this function accept?" It takes a function type and gives you back a tuple type containing all the parameter types in order.
Think of it like looking at a function's signature and copying just the input part into its own type that you can reuse elsewhere.
Basic Syntax
function greet(name: string, age: number): void {
console.log(`Hello ${name}, you are ${age} years old`);
}
type GreetParams = Parameters<typeof greet>;
// Result: [name: string, age: number]
Notice you use typeof to get the function's type, then wrap it with Parameters<>.
Why This Matters
The Parameters utility shines when you need to:
- Build wrapper functions that accept the same arguments as another function
- Extract and reuse parameter types without duplication
- Create type-safe function forwarding or decorators
function logAndCall<T>(
fn: T,
...args: Parameters<T>
): void {
console.log('Calling with:', args);
fn(...args);
}
function add(a: number, b: number): number {
return a + b;
}
logAndCall(add, 5, 3); // Type-safe!
Working with the Tuple Result
The result is a tuple type, so you can access individual parameters by index:
type FirstParam = Parameters<typeof greet>[0]; // string
type SecondParam = Parameters<typeof greet>[1]; // number
You can also spread the tuple into another function signature or use it with rest parameters to maintain perfect type alignment.
Key Takeaway: Parameters<T> extracts a function's parameter types as a tuple, enabling you to reuse argument signatures without repetition and build type-safe function wrappers or utilities that mirror existing function signatures.