Created
February 19, 2026 19:28
-
-
Save svallory/a8c361f9f1139e92ec14cecc69aa27d1 to your computer and use it in GitHub Desktop.
Example of how to properly create a Singleton in Typescript / Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import * as shortid from "shortid"; | |
| import { Type as RealType } from "@tokilabs/lang"; | |
| import { Class } from "./modeling/class"; | |
| import { Type } from "./modeling/type"; | |
| function Singleton<T>(value: T, name?: string): T { | |
| name = name || shortid.generate(); | |
| const SYMBOL = Symbol.for(name); | |
| // check if the global object has this symbol | |
| // add it if it does not have the symbol yet | |
| // ------------------------------------------ | |
| const globalSymbols = Object.getOwnPropertySymbols(global); | |
| if (!(globalSymbols.indexOf(SYMBOL) > -1)) { | |
| global[SYMBOL] = value; | |
| } | |
| // define the singleton API | |
| // ------------------------ | |
| const singleton: { | |
| instance: T; | |
| } = <any>{}; | |
| Object.defineProperty(singleton, "instance", { | |
| get: () => { | |
| return global[SYMBOL]; | |
| }, | |
| }); | |
| // ensure the API is never changed | |
| // ------------------------------- | |
| Object.freeze(singleton); | |
| return singleton.instance; | |
| } | |
| export const ClassRegistry = Singleton( | |
| new Map<RealType, Class>(), | |
| "disl.CLASS_REGISTRY" | |
| ); | |
| export const TypeRegistry = Singleton( | |
| new Map<string | RealType, Type>(), | |
| "disl.TYPE_REGISTRY" | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment