How to get Argument Types from Function in TypeScript ?
Last Updated :
24 Apr, 2025
In TypeScript, the Parameters
utility type allows you to extract the types of a function's parameters. This is particularly useful when you want to work with the types of arguments dynamically, enabling functions that operate on any function's parameter types. In this article, we are going to see how to get argument types from functions in Typescript.
Syntax:
function exampleFunction(arg1: string, arg2: number, arg3: boolean): void {
// Function body
}
// Use the Parameters utility type to get the argument types
type ArgumentTypes = Parameters<typeof exampleFunction>;
function logArgumentTypes(...args: ArgumentTypes): void {
args.forEach(arg => console.log(typeof arg));
}
Approach
- Start by defining the function from which you want to extract the argument types.
- Utilize the
Parameters
utility type to extract the argument types. - Design a function to log the types of arguments.
- Apply the extracted types in your logging function.
Example: In this example, the logArgumentTypes
function uses the typeof
operator to log the type of each argument.
JavaScript
// Define a sample function
function exampleFunction(arg1: string, arg2:
number, arg3: boolean): void {
// Function body
}
type ArgumentTypes = Parameters<typeof exampleFunction>;
function logArgumentTypes(...args: ArgumentTypes):
void {
// Log the type of each argument
args.forEach(arg => console.log(typeof arg));
}
const args: ArgumentTypes = ['Geeks', 22, true];
logArgumentTypes(...args);