TypeScriptUtility types

ConstructorParameters<Type>

Gets the types of a class constructor’s parameters as a tuple.

On this page

Example

#
TypeScript
class Student {
  constructor(public name: string, public level = 1) {}
}

type StudentArgs = ConstructorParameters<typeof Student>
// type StudentArgs = [name: string, level?: number | undefined]

function createMany(rows: StudentArgs[]): Student[] {
  return rows.map((args) => new Student(...args))
}

const students = createMany([['Emma', 4], ['Jack']])
console.log(students)
Result
[Student { name: 'Emma', level: 4 }, Student { name: 'Jack', level: 1 }]

Definition and usage

#

ConstructorParameters<Type> returns a tuple with the types of a constructor’s parameters. It takes the type of the class itself, meaning typeof Badge, not the type of its instance. For constructor(title: string, exp: number) the result is [title: string, exp: number].

It’s the equivalent of Parameters for constructors. It’s useful in factories and functions that create objects on the caller’s behalf: they accept exactly the same arguments as new, so changing the constructor updates their types right away.

It also works with abstract classes and built-in constructors, e.g. ConstructorParameters<ErrorConstructor>. You can pull out a single argument by index: ConstructorParameters<typeof Student>[0].

Syntax

#
Syntax
type Args = ConstructorParameters<typeof Class>

Type parameters

#
  • Type

    constructor type

    The type of a class (typeof Class) or another function called with new.

More examples

#
A generic factory
TypeScript
function make<C extends new (...args: any[]) => any>(
  Cls: C,
  ...args: ConstructorParameters<C>
): InstanceType<C> {
  return new Cls(...args)
}

class Badge {
  constructor(public title: string, public exp: number) {}
}

const badge = make(Badge, '7-day streak', 50)
console.log(badge.title, badge.exp)

make(Badge, '7-day streak')
// Error: Expected 3 arguments, but got 2.
Result
7-day streak 50
A forgotten typeof
TypeScript
type Wrong = ConstructorParameters<Student>
// Error: Type 'Student' does not satisfy the constraint 'abstract new (...args: any) => any'.
//   Type 'Student' provides no match for the signature 'new (...args: any): any'.

Good practices

#
  • Remember the typeof. The class name alone in a type position means the instance, not the constructor.
  • Paired with InstanceType, it describes the whole new call: one type says what goes in, the other what comes out. That’s enough to write a generic factory, as in the second example.

Related entries

#

Spotted a mistake or missing an example? Write to us.