Singleton pattern in TypeScript
23 A singleton with exactly one instance
fairWrite a class following the singleton pattern: a private static instance of itself and a static method returning it. Prove that two calls give you the same object.
Stuck? Three hints, smallest first
- 1. A
private constructoris what stopsnewfrom outside. - 2.
getInstance()creates the object the first time and returns the stored one afterwards. - 3. Compare with
===to prove it is literally the same object, not just an equal one.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
class Settings {
private static instance: Settings | null = null;
private values = new Map<string, string>();
// Private, so `new Settings()` from outside is a compile error.
private constructor() {
this.values.set('theme', 'light');
}
static getInstance(): Settings {
Settings.instance ??= new Settings();
return Settings.instance;
}
set(key: string, value: string): this {
this.values.set(key, value);
return this;
}
get(key: string): string | undefined {
return this.values.get(key);
}
}
const a = Settings.getInstance();
const b = Settings.getInstance();
a.set('theme', 'dark');
console.log('a theme:', a.get('theme'));
console.log('b theme:', b.get('theme')); // the same object, so the same value
console.log('same object?', a === b);
// new Settings(); // error: Constructor of class 'Settings' is private.
test('two calls give one object', a === b, true);
test('a change through a is visible through b', b.get('theme'), 'dark');
test('the default was set in the constructor', Settings.getInstance().get('theme'), 'dark');
test('an unknown key is undefined', a.get('nothing'), undefined);
Output
Settings.instance ??= new Settings() is the whole pattern in one line: assign only if it is currently null or undefined. Worth saying that singletons are easy to overuse; because every caller shares one object, they also share every bug, and they are awkward to reset between tests.