ConstructorParameters<Type>
Gets the types of a class constructor’s parameters as a tuple.
Example
#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)[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
#type Args = ConstructorParameters<typeof Class>Type parameters
#Type
constructor type
The type of a class (typeof Class) or another function called withnew.
More examples
#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.7-day streak 50
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 wholenewcall: 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
#- InstanceType<Type>Gets the type of the object a class constructor creates.
- Parameters<Type>Gets the types of a function’s parameters as a tuple.
- TuplesFixed-length arrays where each position has its own type.
- Generics <T>Types and functions with a type parameter that work for many types without losing precision.
- abstract classA base class you can’t create directly, with methods for its descendants to fill in.
Spotted a mistake or missing an example? Write to us.