TypeScript Reference ยท Utility Types
TypeScript ConstructorParameters<T> utility type
Reference for TypeScript ConstructorParameters<T>: get a class constructor's parameter types as a tuple, for factories, mixins and dependency injection.
ConstructorParameters<T> gives you the parameter list of a constructor type as a tuple. It is the constructor twin of Parameters<T>. Pass it the type of a class (typeof Foo), not the instance type Foo.
It lets generic factories and wrappers accept exactly the arguments a class needs, whatever class they receive.
class User { constructor(public name: string, public age: number) {} } type UserArgs = ConstructorParameters<typeof User>; // [name: string, age: number]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
type ConstructorParameters<T extends abstract new (...args: any) => any> = T extends abstract new (...args: infer P) => any ? P : never;
| Name | Description |
|---|---|
T |
A constructor type, usually typeof SomeClass. Abstract classes are accepted. |
Result: a tuple of the constructor's parameter types, including optional and rest elements. A class with no explicit constructor gives [].
Edge cases: ConstructorParameters<any> is unknown[]. A type that is not constructable, such as an instance type or a plain function, is a compile error.
Usage notes
- Parameter properties count.
constructor(public name: string)contributesname: string, as in the example. - Overloaded constructors: the last overload signature is used.
- Inherited constructors. A subclass without its own constructor reports the parent's parameters.
- Abstract classes work because the constraint includes
abstract new. You cannot instantiate them, but you can read their constructor shape. - Private or protected constructors are not constructor types you can pass to
new, so they are not assignable to the plainnew (...)constraint. - Pair it with
InstanceType: the two together type a factory completely (InstanceType<T>). - Mixins: the constraint
new (...args: any[]) => {}is the standard base for mixin functions;ConstructorParameterspreserves the argument list of the wrapped class. - Available since TypeScript 3.1.
Related
InstanceType<T>,Parameters<T>,ReturnType<T>- Lessons: Classes, Generics