Borislav Hadzhiev
Sat Feb 26 2022·2 min read
Photo by Caroline Hernandez
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.
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.
Here is an example of how you would use the Parameters
utility type for 2
functions that take the same object as a parameter.
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.
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.
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.