Typescript simple singleton

Usage no npm install needed!

<script type="module">
  import offirmoTinySingleton from 'https://cdn.skypack.dev/@offirmo/tiny-singleton';


Tiny singleton
Offirmo’s quality seal

npm badge dependencies badge bundle size badge license badge maintenance status badge

This is a trivial, isomorphic, straightforward, TypeScript-compatible singleton implementation:

  • NO dependencies
  • lazily created on 1st use, as expected


Be sure to review your options before using the singleton pattern. While there are legitimate usages, it can also be a code smell close to a global variable.

// "@offirmo/tiny-singleton": "^0",
import tiny_singleton from '@offirmo/tiny-singleton'

// example: a DB client is a correct case where the singleton pattern can be useful
function create_db_client(ip: string, logger: Console = console): DBClient {
    return ...

// example 1: best semantic
const get_db_client = tiny_singleton(() => create_db_client(''))

// example 2: with params (not recommended as the params will only affect the 1st call, but sometimes convenient)
const get_db_client = tiny_singleton(create_db_client)
// alternative (not better, just an alternative example)
const get_db_client = tiny_singleton((options?: CreationOptions) => create_db_client(options.ip || ''))
get_db_client('') // XXX This will return the same as above!! No new instance creation.