Course contentsShow
← TypeScript
Lesson 706 of 1,79616. Utility TypesFree lesson

Creating Factory Functions from Constructors

Use ConstructorParameters to type-safe factory functions that mirror class constructors.

Creating Factory Functions from Constructors

What you'll learn: How to use ConstructorParameters to create type-safe factory functions that perfectly mirror class constructors.

The Problem

You've already seen how ConstructorParameters<T> extracts constructor parameter types. But knowing the types isn't enough—you often need to use them. A common pattern is building factory functions that create instances without calling new directly, while preserving full type safety for all constructor arguments.

The Pattern

When you create a factory function, you want it to accept the same parameters as the constructor and return an instance. ConstructorParameters<T> makes this bulletproof:

class User {
  constructor(public name: string, public age: number, public active = true) {}
}

// Factory function with exact constructor signature
function createUser(...args: ConstructorParameters<typeof User>): User {
  return new User(...args);
}

const user1 = createUser("Alice", 30);
const user2 = createUser("Bob", 25, false);
// const invalid = createUser("Charlie"); // Error: expected 2-3 arguments

The spread ...args captures all parameters, and TypeScript enforces that callers provide arguments matching the constructor exactly—including optional parameters.

Why This Matters

Without ConstructorParameters, you'd manually duplicate the constructor signature in your factory. If the constructor changes, your factory breaks silently. With this utility, TypeScript keeps them synchronized automatically.

Key Takeaway: ConstructorParameters<T> lets you build factory functions that stay type-safe with their corresponding constructors, eliminating manual synchronization and preventing argument mismatches.