Skip to content

Instantly share code, notes, and snippets.

@Niakr1s
Last active January 29, 2021 10:37
Show Gist options
  • Save Niakr1s/10fe9e30760482c7beedf7cea3788634 to your computer and use it in GitHub Desktop.
Save Niakr1s/10fe9e30760482c7beedf7cea3788634 to your computer and use it in GitHub Desktop.
type Class<Instance extends any> = (new (...args: any[]) => Instance) & { [key: string]: any }
function MySingleton() {
return function decorator<Instance extends any>(constructor: Class<Instance>) {
let instance: Instance | null = null
let decoratedConstructor = function (...args: any[]) {
if (!instance) {
instance = new constructor(...args)
}
return instance
} as Function as Class<Instance>
decoratedConstructor.prototype = constructor.prototype
return decoratedConstructor as Class<Instance>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment