Get the Type of a Function's Arguments in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 26, 2022

banner

Photo from Unsplash

Get the Type of a Function's Arguments in TypeScript #

Use the Parameters utility type to get the type of a function's arguments, e.g. type SumParams = Parameters<typeof sum>. The Parameters utility type constructs a tuple type from the types used in the function's parameters.

index.ts
function sum(a: number, b: string): string { return a + b; } // 👇️ type SumParams = [a: number, b: string] type SumParams = Parameters<typeof sum>; // 👇️ type FirstParam = number type FirstParam = SumParams[0]; // 👇️ type SecondParam = string type SecondParam = SumParams[1];

The Parameters utility type constructs a tuple type from the types used in the function's parameters.

You can access the type of a specific parameter by using square brackets, in the same way you would access an array element at index.

Here is an example of how you would use the Parameters utility type for 2 functions that take the same object as a parameter.

index.ts
type Person = { name: string; age: number; country: string; }; function getObj(obj: Person): Person { return obj; } function getObj2(obj: Parameters<typeof getObj>[0]) { return obj; } console.log(getObj2({ name: 'Tom', age: 30, country: 'Chile' }));

The getObj2 function takes an object of the same type as the one the getObj function takes.

Notice that after we get the tuple of parameter types, we have to access the element at index 0 to get the type of the object.

index.ts
type Person = { name: string; age: number; country: string; }; function getObj(obj: Person): Person { return obj; } // 👇️ type GetObjParams = [obj: Person] type GetObjParams = Parameters<typeof getObj>

This is because the Parameters utility type returns a tuple, even if the function takes a single parameter.

If you need to get the types of the parameters of a constructor method in a class, use the ConstructorParameters utility type instead.

index.ts
class Person { constructor(public name: string, public age: number) { this.name = name; this.age = age; } } // 👇️ type PersonParams = [name: string, age: number] type PersonParams = ConstructorParameters<typeof Person>; // 👇️ type FirstParam = string type FirstParam = PersonParams[0]; // 👇️ type SecondParam = number type SecondParam = PersonParams[1];

The ConstructorParameters utility types constructs a tuple from the types of a constructor function's parameters.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.