TypeScript ConstructorParameters<T> Utility Type Explained
Learn how ConstructorParameters<T> extracts a class constructor's parameter types as a tuple. Examples for factory functions and dependency injection.
Detailed Explanation
Understanding ConstructorParameters
ConstructorParameters<T> constructs a tuple type from the parameter types of a constructor function type. It is the constructor equivalent of Parameters.
Syntax
type ConstructorParameters<T extends abstract new (...args: any) => any> =
T extends abstract new (...args: infer P) => any ? P : never;
Basic Example
class ApiClient {
constructor(
public baseUrl: string,
public timeout: number,
public headers: Record<string, string>
) {}
}
type ClientArgs = ConstructorParameters<typeof ApiClient>;
// Result: [baseUrl: string, timeout: number, headers: Record<string, string>]
Practical Pattern: Factory with Defaults
function createWithDefaults<T extends new (...args: any[]) => any>(
Ctor: T,
defaults: Partial<Record<number, ConstructorParameters<T>[number]>>
): (...args: ConstructorParameters<T>) => InstanceType<T> {
return (...args) => new Ctor(...args);
}
With Built-in Types
type DateArgs = ConstructorParameters<typeof Date>;
// Result: [value: string | number | Date] (one overload)
type ErrorArgs = ConstructorParameters<typeof Error>;
// Result: [message?: string, options?: ErrorOptions]
type RegExpArgs = ConstructorParameters<typeof RegExp>;
// Result: [pattern: string | RegExp, flags?: string]
Practical Pattern: Testing Helpers
class UserService {
constructor(
private db: Database,
private mailer: Mailer,
private logger: Logger
) {}
}
type ServiceDeps = ConstructorParameters<typeof UserService>;
// [db: Database, mailer: Mailer, logger: Logger]
function createTestService(
...overrides: Partial<ServiceDeps>
): UserService {
const defaults: ServiceDeps = [mockDb, mockMailer, mockLogger];
const args = defaults.map((d, i) => overrides[i] ?? d);
return new UserService(...(args as ServiceDeps));
}
Use Case
Use ConstructorParameters<T> when building factory functions, dependency injection containers, test helpers that mock constructor arguments, or any utility that needs to know what a class constructor expects.
Try It — TypeScript Utility Types
Related Topics
TypeScript InstanceType<T> Utility Type Explained
Function Types
TypeScript Parameters<T> Utility Type Explained
Function Types
TypeScript ReturnType<T> Utility Type Explained
Function Types
Composing Multiple TypeScript Utility Types
Advanced Patterns
TypeScript Pick<T, K> Utility Type Explained
Object Types