How to get Argument Types from Function in TypeScript ?
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 = [ 'Beginner' , 22, true ]; logArgumentTypes(...args); |
Output:
string
number
boolean
Example 2: In this example, the printNumberTypes
function now correctly logs the type of each number using the typeof
operator.
Javascript
function addNumbers(a: number, b: number): number { return a + b; } type AddNumbersArgs = Parameters< typeof addNumbers>; function printNumberTypes(...numbers: AddNumbersArgs): void { numbers.forEach(num => console.log( typeof num)); } const result: AddNumbersArgs = [10, 20]; printNumberTypes(...result); |
Output:
number
number