Type generic class factories
A factory or dependency-injection wrapper accepts a class and needs to type its argument list consistently with that class.
TypeScript · Type Alias
ConstructorParameters<Type> extracts the parameter types of a constructor as a tuple or array. It is useful for reusing and checking constructor arguments without duplicating their declarations.
ConstructorParameters<T> inspects a constructible type and returns the argument types accepted by its constructor as a tuple or array. For an unsupported type it yields never, while any produces unknown[]; the referenced type must satisfy the abstract construct-signature constraint.
type ConstructorParameters<Type extends abstract new (...args: any) => any> = ...| Name | Type | Description |
|---|---|---|
Type | abstract new (...args: any) => any | A type with an abstract construct signature, such as typeof a class constructor. |
A tuple or array containing the constructor parameter types; never for a non-function input, with any producing unknown[].
class User {
constructor(public name: string, public age: number) {}
}
type UserConstructorArgs = ConstructorParameters<typeof User>;
const args: UserConstructorArgs = ["Ada", 36];
const user = new User(...args);
console.log(user.name, user.age);The tuple extracted from the class constructor can be checked before being spread into a new instance.
A factory or dependency-injection wrapper accepts a class and needs to type its argument list consistently with that class.
A registry stores constructors and separately stores argument tuples that must remain compatible with instantiation.
A refactor changes a class constructor and dependent code should receive compile-time errors instead of maintaining duplicated parameter types.
It extracts a tuple or array containing the parameter types of a constructor function type. For example, ConstructorParameters<typeof C> represents the arguments accepted by class C.
Follow-up: How does it handle an abstract class? TypeScript 4.3 added support, so an abstract class constructor can be used and its constructor parameters are extracted.
The type argument is constrained to an abstract construct signature, so it must describe something callable with new. If the input is not a function type, the documented result is never, subject to the constraint being satisfied.
Follow-up: What happens with any? The utility produces unknown[] rather than a precisely typed tuple.
For an ordinary class, use typeof ClassName because that is the constructor value type; the instance type alone does not describe the construct signature. The resulting tuple preserves parameter types and labels shown in the constructor declaration.
Follow-up: How are overloaded constructors treated? The extracted parameters correspond to the last signature.
ParametersInstanceTypeReturnTypeabstract new (...args: any) => any