← Back to TypeScript Course | Chapter 8: Advanced Types | Lesson 19 of 20

Utility Types - Parameters

Parameters<T> extracts a function's parameter types as a tuple. It is useful when another type or function needs to reuse an existing function's argument structure.

Basic Parameters

Parameters<T> returns a tuple type containing the types of a function type T's parameters, in the same order they appear in the function's own signature. It's one of the most common utility types for building wrapper or higher-order functions that mirror an existing signature.

Example: Basic Parameters

typescript
function createUser(name: string, age: number) {
  return { name, age };
}
type CreateUserArgs = Parameters<typeof createUser>;
const args: CreateUserArgs = ["Ravi", 25];
console.log(createUser(...args));

Parameters with Arrow Functions

Parameters works with arrow functions in the same way it works with regular function declarations, since both produce the same kind of function type under the hood.

Example: Parameters with Arrow Functions

typescript
const add = (a: number, b: number) => a + b;
type AddArgs = Parameters<typeof add>;
const args: AddArgs = [2, 3];
console.log(add(...args));

Parameters with Optional Arguments

Parameters preserves optional parameters in the resulting tuple, marking the corresponding tuple positions as optional just as they were in the original function signature.

Example: Parameters with Optional Arguments

typescript
function greet(name: string, greeting?: string) {
  return `${greeting ?? "Hello"}, ${name}`;
}
type GreetArgs = Parameters<typeof greet>;
const args: GreetArgs = ["Ravi"];
console.log(greet(...args));

Parameters with Rest Arguments

Parameters can extract rest parameters as part of the resulting tuple or array structure, reflecting a variadic function's actual calling convention, including any trailing array-typed rest argument.

Example: Parameters with Rest Arguments

typescript
function sum(first: number, ...rest: number[]) {
  return first + rest.reduce((a, b) => a + b, 0);
}
type SumArgs = Parameters<typeof sum>;
const args: SumArgs = [1, 2, 3];
console.log(sum(...args));

When to Use Parameters

Use Parameters when a type needs to stay synchronized with an existing function's argument list, such as building a wrapper or mock that must always match the original function's signature.

Example: When to Use Parameters

typescript
function original(a: number, b: string) {
  return `${a}-${b}`;
}
function wrapper(...args: Parameters<typeof original>) {
  console.log("Calling with", args);
  return original(...args);
}
console.log(wrapper(1, "x"));

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.