Patterns & principles · 3 of 10 · 15 min read
The Singleton pattern
One instance, and the four ways TypeScript spells it — plus the honest case that the pattern is usually the wrong answer and injection is the right one.
- Design patterns
Singleton means: exactly one instance, reachable from anywhere. TypeScript can enforce the “one instance” part properly — and the pattern is still, most of the time, a worse version of passing the thing in.
The four spellings
// 1. An exported const. A module is evaluated once.
export const logger = { log: (message: string) => console.log(message) };
// 2. A class with a private constructor and a lazy instance.
class Config {
private static instance: Config | undefined;
private constructor(readonly values: Readonly<Record<string, string>>) {}
static getInstance(): Config {
Config.instance ??= new Config({ env: "production" });
return Config.instance;
}
}
// new Config({}); // the constructor is private
console.log(Config.getInstance() === Config.getInstance()); // true
// 3. A static-only class — no instance at all.
class Counter {
static #count = 0;
private constructor() {} // not instantiable
static increment() { return ++Counter.#count; }
static get value() { return Counter.#count; }
}
Counter.increment();
console.log(Counter.value); // 1
// 4. A factory that caches, which is the testable version.
interface Cache { get(key: string): string | undefined; set(key: string, value: string): void }
let shared: Cache | undefined;
export function createCache(): Cache {
const store = new Map<string, string>();
return { get: (key) => store.get(key), set: (key, value) => void store.set(key, value) };
}
export function getSharedCache(): Cache {
return (shared ??= createCache());
}
export function resetSharedCache(): void {
shared = undefined; // the seam a test needs
}
| Spelling | One instance | Testable | Lazy | Notes |
|---|---|---|---|---|
Exported const |
yes | hard to replace | no — created at import | the simplest, and usually enough |
private constructor + getInstance |
enforced | hard | yes | the textbook form |
| Static-only class | n/a — no instances | hard | n/a | a namespace with extra steps |
| Factory + cached accessor | by convention | yes, via the factory | yes | the one to prefer |
The fourth row is the recommendation. It keeps the convenience of a shared instance while leaving
createCache() available, so a test constructs its own and never touches the shared one.
What private constructor buys
class WithoutPrivate {
static instance = new WithoutPrivate();
}
const sneaky = new WithoutPrivate(); // nothing prevented this
class WithPrivate {
static readonly instance = new WithPrivate();
private constructor() {}
}
// const also = new WithPrivate(); // Constructor of class 'WithPrivate' is private
console.log(sneaky instanceof WithoutPrivate, WithPrivate.instance instanceof WithPrivate);
It is a compile-time check, like every other access modifier — (WithPrivate as any) still gets
through at runtime. That is enough for the purpose: the point is to stop a colleague writing a
second new by accident, not to defend against someone determined.
private constructor also makes the class non-extendable, because a subclass cannot call super().
Use protected constructor when a subclass is meant to exist.
A generic singleton registry
When several services each want one instance, one typed registry beats a getInstance on each:
type Registry = {
logger: { log(message: string): void };
cache: { get(key: string): unknown };
};
const instances: { [K in keyof Registry]?: Registry[K] } = {};
const factories: { [K in keyof Registry]: () => Registry[K] } = {
logger: () => ({ log: (message) => console.log(message) }),
cache: () => ({ get: () => undefined }),
};
function resolve<K extends keyof Registry>(key: K): Registry[K] {
return (instances[key] ??= factories[key]()) as Registry[K];
}
function override<K extends keyof Registry>(key: K, value: Registry[K]): void {
instances[key] = value; // what a test calls
}
resolve("logger").log("ready");
override("logger", { log: () => {} });
console.log(typeof resolve("cache").get);
This is a container in 15 lines, and it is the step between “singletons everywhere” and a
dependency-injection framework. Registry[K] is what keeps resolve("logger") typed as the
logger rather than as a union.
Why it is usually the wrong answer
Three concrete problems, all of which show up as test pain first:
Hidden dependencies. A function that calls Config.getInstance() depends on the config, and
its signature does not say so. Nothing can tell you what a module needs without reading its body.
// The dependency is invisible:
declare const Config: { getInstance(): { values: { apiUrl: string } } };
function loadBad(path: string) {
return fetch(Config.getInstance().values.apiUrl + path);
}
// The dependency is in the signature:
interface Deps { apiUrl: string }
function loadGood(deps: Deps, path: string) {
return fetch(deps.apiUrl + path);
}
console.log(typeof loadBad, typeof loadGood);
Shared state between tests. A singleton persists across test cases in the same process, so a mutation in one leaks into the next and the failure depends on test order. Every workaround is a reset hook that somebody forgets to call.
Initialisation order. A singleton created at import time runs before anything has configured it, which turns module load order into program behaviour — and module load order is decided by a bundler.
The replacement is boring and works: create the thing once at the top of the application, and pass it to whatever needs it.
interface Logger { log(message: string): void }
interface Database { query(sql: string): Promise<unknown[]> }
class UserService {
constructor(
private readonly db: Database,
private readonly logger: Logger,
) {}
async find(id: string) {
this.logger.log(`finding ${id}`);
return this.db.query(`select * from users where id = '${id}'`);
}
}
// One place composes the application:
declare const db: Database;
const logger: Logger = { log: (message) => console.log(message) };
const users = new UserService(db, logger);
// A test composes a different one, with no reset and no mocking framework:
const captured: string[] = [];
const testUsers = new UserService(
{ query: async () => [] },
{ log: (message) => captured.push(message) },
);
console.log(typeof users.find, typeof testUsers.find);
Parameter properties make the constructor two lines, and the dependencies are now in the type.
When a singleton is fine
The pattern is not always wrong. It is reasonable when the thing is stateless or append-only, and when there is genuinely one of it in the process:
- A logger that writes to stdout.
- A connection pool, where the whole point is that there is one.
- A read-only configuration object, frozen after initialisation.
- A cache whose correctness does not depend on being empty.
The test to apply: would two of these be a bug, and does a test ever need a different one? If the answer to the second question is yes — which it is for anything stateful — expose the factory alongside the shared instance.
Common mistakes
getInstance without a private constructor
Mistake. A static getInstance() on a class with a public constructor.
Why it fails. Nothing enforces anything; the “singleton” is a suggestion, and the second
instance appears in the code someone writes next month.
What to do instead. private constructor, or drop the class and export a const.
A singleton holding mutable state in tests
Mistake. Config.getInstance().values.token = "test" in a test setup.
Why it fails. The mutation outlives the test, so the next one passes or fails depending on
order — the hardest kind of flake to diagnose.
What to do instead. Construct an instance per test and inject it, or expose an explicit reset
and call it in a teardown.
A class with nothing but statics
Mistake. class MathUtils { static clamp() {} static lerp() {} }.
Why it fails. It is a namespace wearing a class costume: nothing is tree-shaken, nothing can
be imported individually, and new MathUtils() is still legal unless the constructor is private.
What to do instead. Export the functions from a module. import * as MathUtils gives the same
call sites.
Check yourself
One question from the bank on what you just read. Answering here does not affect your quiz history.
What is the typed equivalent of the Singleton pattern in TypeScript?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.