0
0
Typescriptprogramming~5 mins

ConstructorParameters type in Typescript

Choose your learning style9 modes available
Introduction

The ConstructorParameters type helps you get the list of input types a class constructor needs. It makes working with classes easier and safer.

When you want to create a new instance of a class but only know the class type, not the constructor details.
When you want to write a function that accepts constructor arguments of any class.
When you want to copy or forward constructor arguments from one class to another.
When you want to extract constructor argument types for documentation or validation.
Syntax
Typescript
ConstructorParameters<Type>

Type must be a class constructor type.

The result is a tuple type representing the constructor's parameter types.

Examples
This example extracts the constructor parameters of Person as a tuple type.
Typescript
class Person {
  constructor(name: string, age: number) {}
}
type PersonParams = ConstructorParameters<typeof Person>;
// PersonParams is [string, number]
Optional parameters in the constructor are reflected in the tuple type.
Typescript
class Car {
  constructor(make: string, year?: number) {}
}
type CarParams = ConstructorParameters<typeof Car>;
// CarParams is [string, (number | undefined)?]
You can use ConstructorParameters with any constructor type, not just classes.
Typescript
type Params = ConstructorParameters<new (x: boolean) => any>;
// Params is [boolean]
Sample Program

This program uses ConstructorParameters to get the constructor argument types of Book. Then it creates a new Book instance safely with those arguments.

Typescript
class Book {
  constructor(title: string, pages: number) {
    this.title = title;
    this.pages = pages;
  }
  title: string;
  pages: number;
}

function createInstance<T extends new (...args: any) => any>(ctor: T, args: ConstructorParameters<T>) {
  return new ctor(...args);
}

const bookArgs: ConstructorParameters<typeof Book> = ["Learn TypeScript", 250];
const myBook = createInstance(Book, bookArgs);
console.log(myBook.title);
console.log(myBook.pages);
OutputSuccess
Important Notes

If the constructor has no parameters, ConstructorParameters returns an empty tuple [].

This type only works with class constructors or constructor signatures, not regular functions.

Summary

ConstructorParameters extracts the types of a class constructor's parameters as a tuple.

It helps write safer and more flexible code when working with class instances.

Use it when you want to forward or reuse constructor argument types.