Private Constructors Pattern
What you'll learn: How to prevent direct instantiation of classes and force users to create objects only through controlled factory methods.
The Core Idea
The Private Constructors Pattern uses TypeScript's private access modifier on a class constructor to make it impossible to call new MyClass() from outside the class. This forces all object creation to go through static factory methods that you define, giving you complete control over how instances are created, validated, and returned.
This pattern is especially powerful when combined with opaque types and smart constructors — you can ensure that invalid objects never exist, because the only way to create them is through your validation logic.
Basic Syntax
class Email {
private constructor(private readonly value: string) {}
static create(input: string): Email | null {
if (!input.includes('@')) {
return null;
}
return new Email(input);
}
getValue(): string {
return this.value;
}
}
// ❌ Error: Constructor is private
// const email = new Email("test");
// ✅ Must use factory method
const email = Email.create("user@example.com");
if (email) {
console.log(email.getValue());
}
Why This Matters
Think of the private constructor like a locked factory door. You can't just walk in and grab a product off the assembly line — you must go through the front desk (the factory method), where quality control happens. This ensures every product that leaves the factory meets your standards.
Without this pattern, users could create invalid objects by calling the constructor directly. With it, you guarantee that all instances pass through your validation, parsing, or transformation logic.
Real-World Example: Safe ID Type
type UserId = string & { readonly __brand: unique symbol };
class User {
private constructor(private readonly id: UserId) {}
static fromId(rawId: string): User | null {
if (rawId.length === 0 || rawId.length > 50) {
return null;
}
return new User(rawId as UserId);
}
getId(): UserId {
return this.id;
}
}
// The only way to create a User is through validated factory
const user = User.fromId("user-123");
Here, the private constructor ensures that UserId values are always validated before any User instance exists. You've made impossible states impossible to construct.
Key Takeaway: Private constructors enforce that only your static factory methods can create instances, guaranteeing that all objects pass through validation and making invalid states impossible to construct.