Classes and Object-Oriented TypeScriptLesson 5.3
Static members and singleton pattern in TypeScript
static properties, static methods, class-level vs instance-level, static blocks, singleton pattern implementation
Static members
Static members belong to the class, not to instances:
class MathUtils {
static readonly PI = 3.14159;
static circleArea(radius: number): number {
return MathUtils.PI * radius ** 2;
}
}
MathUtils.circleArea(5); // no instance neededSingleton pattern
Use a private constructor and a static instance to enforce a single object:
class Config {
private static instance: Config | null = null;
private data: Record = {};
private constructor() {}
static getInstance(): Config {
if (!Config.instance) {
Config.instance = new Config();
}
return Config.instance;
}
set(key: string, value: string): void { this.data[key] = value; }
get(key: string): string | undefined { return this.data[key]; }
}
const cfg = Config.getInstance();
cfg.set("env", "production");