Skip to content

Instantly share code, notes, and snippets.

@piouson
Created April 16, 2024 10:29
Show Gist options
  • Save piouson/4cc9697a5050d8fd88e5e5936fc55412 to your computer and use it in GitHub Desktop.
Save piouson/4cc9697a5050d8fd88e5e5936fc55412 to your computer and use it in GitHub Desktop.
Typescript Singleton function with code splitting
type Singleton = {
done(): void;
};
type SingletonContructor = {
new (): Singleton;
(): Singleton;
staticDone(): void;
};
// export functions for code splitting
export function done() {
console.log("Singleton function");
}
export function staticDone() {
console.log("Static function");
}
const singleton = (function () {
let instance: Singleton;
const Singleton = function (this: Singleton) {
if (instance) return instance;
instance = new.target ? this : new Singleton();
return instance;
} as SingletonContructor;
Singleton.prototype.done = done;
Singleton.staticDone = staticDone;
return Singleton;
})();
singleton.staticDone(); // Static function
new singleton().done(); // Singleton function
const eg1 = singleton();
const eg2 = new singleton();
console.log(`eg1 === eg2 ? ${eg1 === eg2}`); // eg1 === eg2 ? true
eg1.done(); // Singleton function
eg2.done(); // Singleton function
export default singleton;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment