Common Static Patterns
What you'll learn: How to leverage static class members to implement factory methods, singleton patterns, and utility functions — three powerful design patterns that organize functionality without requiring instance creation.
Understanding Static Patterns
Static members shine when you have functionality that belongs conceptually to a class but doesn't need instance data. Three patterns dominate real-world TypeScript:
1. Factory Methods
Factory methods are static methods that construct instances using custom logic, providing clearer intent than new and encapsulating complex initialization:
class User {
constructor(
public username: string,
private passwordHash: string
) {}
static fromCredentials(username: string, password: string): User {
const hash = `hashed_${password}`; // Simplified hashing
return new User(username, hash);
}
static guest(): User {
return new User("guest", "");
}
}
const user = User.fromCredentials("alice", "secret123");
const guestUser = User.guest();
2. Singleton Pattern
The singleton ensures only one instance exists, using a private constructor and static access method:
class Logger {
private static instance: Logger;
private constructor() {} // Prevents `new Logger()`
static getInstance(): Logger {
if (!Logger.instance) {
Logger.instance = new Logger();
}
return Logger.instance;
}
log(message: string): void {
console.log(`[LOG] ${message}`);
}
}
const logger1 = Logger.getInstance();
const logger2 = Logger.getInstance(); // Same instance
3. Utility Functions
Pure functions that relate to a class's domain but don't modify state work perfectly as static methods:
class Temperature {
constructor(public celsius: number) {}
static fromFahrenheit(f: number): Temperature {
return new Temperature((f - 32) * 5 / 9);
}
static celsiusToFahrenheit(c: number): number {
return (c * 9 / 5) + 32;
}
}
const temp = Temperature.fromFahrenheit(98.6);
const converted = Temperature.celsiusToFahrenheit(25); // 77
When These Patterns Fit
Use factory methods for alternative constructors, singletons for global shared resources (use sparingly!), and static utilities for stateless operations that group naturally with a class.
Key Takeaway: Static members excel at factory methods (alternative construction), singletons (controlled single instances), and utility functions (stateless helpers) — organizing functionality at the class level without requiring instantiation.