TypeScript

Lazy Singleton (no class)

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Lazily construct an expensive object exactly once, with TypeScript inferring the return type from the factory. Cleaner than the class-trait singleton pattern for module-scoped state.
TypeScript
Raw
export function lazy<T>(factory: () => T): () => T {
  let cached: T | undefined;
  let initialized = false;
  return () => {
    if (!initialized) {
      cached = factory();
      initialized = true;
    }
    return cached as T;
  };
}

// Module-scoped lazy singleton — DB connection
const getDb = lazy(() => {
  console.log('Connecting to DB…');           // logged exactly once
  return new DatabaseClient(process.env.DATABASE_URL!);
});

// Anywhere in the codebase:
const db = getDb();   // first call: opens connection
const db2 = getDb();  // subsequent calls: returns the same instance
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.