Extracting Constructor Parameter Types
What you'll learn: How to use conditional types with infer to extract the parameter types from a class constructor, giving you type-safe access to what arguments a class expects.
Why Extract Constructor Parameters?
Sometimes you need to know what parameters a class constructor accepts without actually instantiating the class. Maybe you're building a factory function, a dependency injection container, or a testing utility. Instead of manually duplicating the constructor's parameter list, TypeScript lets you extract it automatically using conditional types and infer.
The Constructor Pattern
To extract constructor parameters, you need to match against a constructor signature. In TypeScript, constructors have a special form:
new (...args: SomeType[]) => InstanceType
By using infer in a conditional type, you can capture the SomeType[] tuple that represents the constructor's parameters.
The Basic Pattern
type ExtractConstructorParams<T> = T extends new (...args: infer P) => any
? P
: never;
class User {
constructor(public name: string, public age: number) {}
}
type UserParams = ExtractConstructorParams<typeof User>;
// UserParams is [name: string, age: number]
The pattern breaks down like this:
T extends new (...args: infer P) => anychecks ifTis a constructorinfer Pcaptures the parameter tuple- If it matches, return
P; otherwise, returnnever
Why This Works
The new (...args: infer P) pattern tells TypeScript: "If this type is a constructor that accepts some arguments, capture those arguments as P." The => any part means "we don't care what instance type it creates—just give us the parameters."
Think of it like asking: "What ingredients does this recipe need?" You don't care what dish it makes; you just want the shopping list.
Practical Use Case
function createInstance<T>(
constructor: new (...args: ExtractConstructorParams<typeof constructor>) => T,
...args: ExtractConstructorParams<typeof constructor>
): T {
return new constructor(...args);
}
const user = createInstance(User, "Alice", 30);
// TypeScript knows you need a string and number
Key Takeaway: Use T extends new (...args: infer P) => any ? P : never to extract constructor parameter types as a tuple, enabling type-safe factory functions and reflection-like patterns without runtime overhead.