Borislav Hadzhiev
Sat Feb 26 2022·2 min read
Photo by Saksham Gangwar
Use the ConstructorParameters
utility type to get the type of a constructor
function's arguments. The ConstructorParameters
utility types constructs a
tuple from the types of a constructor function's parameters.
class Employee { constructor(public name: string, public salary: number) { this.name = name; this.salary = salary; } } // 👇️ type EmployeeParams = [name: string, salary: number] type EmployeeParams = ConstructorParameters<typeof Employee>; // 👇️ type FirstParam = string type FirstParam = EmployeeParams[0]; // 👇️ type SecondParam = number type SecondParam = EmployeeParams[1];
The ConstructorParameters utility types constructs a tuple from the types of a constructor function's parameters.
Here is an example of using ConstructorParameters
with a constructor that
takes an object as a parameter.
class Employee { constructor(public obj: { name: string; salary: number }) { this.obj = obj; } } // 👇️ type EmployeeParams = [obj: { name: string; salary: number;}] type EmployeeParams = ConstructorParameters<typeof Employee>; // 👇️ type FirstParam = { name: string; salary: number;} type FirstParam = EmployeeParams[0];
Notice that even though the constructor takes a single parameter, we still get a
tuple containing the object's type from the ConstructorParameters
utility
type.
If you need to get the type of the object, access the tuple element at index
0
.
If you need to get the types of the arguments of a basic function, use the Parameters utility type instead.
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.