Course contentsShow
← TypeScript
Lesson 1342 of 1,79631. Type-Driven DesignFree lesson

Never Allow Partial Construction

Using private constructors and factory functions to ensure objects are always fully valid when created.

Never Allow Partial Construction

What you'll learn: How to use private constructors and factory functions to prevent objects from being created in an invalid, half-initialized state.

The Problem with Public Constructors

When you expose a public constructor, TypeScript can't prevent callers from creating an object and then trying to use it before all required setup is complete. Even with type annotations, you might have objects that are technically typed correctly but logically invalid.

Think of it like a car factory: you wouldn't let a car roll off the assembly line with the engine installed but no wheels. The car "object" exists, but it's not in a usable state.

The Solution: Private Constructor + Factory Function

By making your constructor private, you prevent direct instantiation. Instead, you provide a factory function (usually a static method) that performs all necessary validation and setup before creating the instance.

The factory function becomes your gatekeeper—it ensures that by the time an object exists, it's guaranteed to be fully valid.

Key Pattern

Here's the core structure:

class User {
  private constructor(
    private readonly id: string,
    private readonly email: string
  ) {}

  static create(id: string, email: string) {
    // Validation happens BEFORE construction
    if (!email.includes('@')) {
      throw new Error('Invalid email');
    }
    if (id.length === 0) {
      throw new Error('ID cannot be empty');
    }
    
    // Only create the object once validation passes
    return new User(id, email);
  }
}

// User.create('123', 'alice@example.com'); ✓
// new User('123', 'bad-email'); ✗ Constructor is private

With this pattern, it's impossible to have a User object with an invalid email. The type system enforces that only valid instances can exist.

Key Takeaway: Private constructors combined with factory functions ensure that objects are always fully validated and in a legal state when created—making invalid states unrepresentable at the type level.