Skip to main content

Command Palette

Search for a command to run...

Singleton in TypeScript

Published
1 min readView as Markdown
Singleton in TypeScript
V

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.

More from this blog

V

Vijay Thirugnanam

38 posts

Short technical tips. Mostly stuff that I can refer to later.