typescript
38 lines · 7 steps
A module-scoped Singleton in TypeScript
Module caching guarantees one shared ConfigManager instance, with typed get/set accessors over a private config object.
Explained by
highlit
1// A module-scoped Singleton: the single instance lives in this module's
2// closure and is never exposed directly.
3
4interface AppConfig {
5 apiUrl: string;
6 retries: number;
7}
8
9class ConfigManager {
10 private config: AppConfig;
11
12 constructor() {
13 this.config = {
14 apiUrl: process.env.API_URL ?? "http://localhost:3000",
15 retries: Number(process.env.RETRIES ?? 3),
16 };
17 }
18
19 get<K extends keyof AppConfig>(key: K): AppConfig[K] {
20 return this.config[key];
21 }
22
23 set<K extends keyof AppConfig>(key: K, value: AppConfig[K]): void {
24 this.config[key] = value;
25 }
26
27 snapshot(): Readonly<AppConfig> {
28 return Object.freeze({ ...this.config });
29 }
30}
31
32// Instantiated once at module load; module caching guarantees a single
33// instance shared across every importer.
34const instance = new ConfigManager();
35
36export function getConfigManager(): ConfigManager {
37 return instance;
38}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1ES modules are cached, so a const initialized at load time becomes a natural singleton without any locking.
- 2Keying generics on `keyof` ties an accessor's return type to the property you ask for, catching typos at compile time.
- 3Returning a frozen shallow copy lets callers read state safely without mutating the source of truth.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-module-scoped-singleton-in-typescript-explained-typescript-9845/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.