Singleton in TypeScript

Engineer working in Cerebras. Latest work is Cerebras Inference. I love writing code in React, TypeScript, C++, Python. I spend most of my work hours tinkering with code.
Some example code on how to write a singleton in TypeScript.
/* eslint-disable no-var */
declare global {
var _singleton: SingletonClass
}
/* eslint-enable no-var */
// Only one instance for the process in production
if (!globalThis._singleton) {
globalThis._singleton = new SingletonClass()
}
const singleton: SingletonClass = globalThis._singleton
export default singleton
In the above code, SingletonClass represents the class whose object you want to make a singleton. globalThis is a typescript variable that points to “window” in browser environment and “global” in Node environment.
