Get the Type of a Constructor function's Arguments in TS

avatar

Borislav Hadzhiev

Last updated: Feb 26, 2022

banner

Photo from Unsplash

Get the Type of a Constructor function's Arguments in TS #

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.

index.ts
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.

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 using ConstructorParameters with a constructor that takes an object as a parameter.

index.ts
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.

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.

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.