TypeScript Parameters<T> Utility Type Explained
Learn how Parameters<T> extracts a function's parameter types as a tuple. Examples for forwarding arguments, creating wrappers, and type-safe event handlers.
Detailed Explanation
Understanding Parameters
Parameters<T> constructs a tuple type from the parameter types of function type T. It lets you extract and reuse a function's parameter list.
Syntax
type Parameters<T extends (...args: any) => any> =
T extends (...args: infer P) => any ? P : never;
Basic Example
function sendEmail(
to: string,
subject: string,
body: string,
options?: { cc?: string; bcc?: string }
): void {}
type EmailParams = Parameters<typeof sendEmail>;
// Result: [to: string, subject: string, body: string, options?: { cc?: string; bcc?: string }]
type FirstParam = EmailParams[0]; // string
type OptionsParam = EmailParams[3]; // { cc?: string; bcc?: string } | undefined
Practical Pattern: Wrapper Functions
function withLogging<T extends (...args: any[]) => any>(
fn: T
): (...args: Parameters<T>) => ReturnType<T> {
return (...args: Parameters<T>) => {
console.log("Calling with:", args);
const result = fn(...args);
console.log("Result:", result);
return result;
};
}
const loggedSendEmail = withLogging(sendEmail);
// Fully typed -- same parameters as sendEmail
Practical Pattern: Event Handler Types
type EventMap = {
click: (x: number, y: number) => void;
keypress: (key: string, modifiers: string[]) => void;
resize: (width: number, height: number) => void;
};
function emit<K extends keyof EventMap>(
event: K,
...args: Parameters<EventMap[K]>
): void {
// type-safe event emission
}
emit("click", 100, 200); // OK
emit("keypress", "Enter", ["Ctrl"]); // OK
// emit("click", "wrong"); // Error!
Use Case
Use Parameters<T> when building function wrappers, middleware, decorator patterns, type-safe event emitters, or any utility that needs to forward a function's arguments with full type safety.
Try It — TypeScript Utility Types
Related Topics
TypeScript ReturnType<T> Utility Type Explained
Function Types
TypeScript ConstructorParameters<T> Utility Type Explained
Function Types
TypeScript InstanceType<T> Utility Type Explained
Function Types
Composing Multiple TypeScript Utility Types
Advanced Patterns
TypeScript Exclude<T, U> vs Extract<T, U> Explained
Union Types