[Typescript] Singleton helper method

export function singleton<
	T extends new (...args: any[]) => object
>(classCtor: T): T {
	let instance!: InstanceType<T>

	const proxy = new Proxy(classCtor, {
		construct(target, args, newTarget) {
			if (!instance) {
				// Reflect.construct(...) returns 'unknown' by default,
				// so we explicitly cast to InstanceType<T>.
				instance = Reflect.construct(target, args, newTarget) as InstanceType<T>
			}
			// Must return an object, so returning 'instance' is fine.
			return instance
		},
	})

	// If you really need to modify the prototype’s constructor property:
	classCtor.prototype.constructor = proxy

	// Cast the Proxy object back to T so it’s recognized as a valid constructor.
	return proxy as T
}

 

// myclass.ts
class MyClass {}
const mySinClass = singleton(MyClass)

// main.ts
import { mySinClass } from "myclass"

console.log(mySinClass === new mySinClass.constructor()) // true

 

posted @   Zhentiw  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
历史上的今天:
2024-03-04 [Rust] ref keyword for borrow value
2024-03-04 [Rust] if let & while let
2024-03-04 [Rust] Using .map_err instead of wrap which cause panic
2024-03-04 [Rust] Using Box<dyn error::Error>> return one of miultiple error types at runtime
2022-03-04 [AWS Explained] Security
2020-03-04 [AST Babel] Babel Template
2020-03-04 [HTML5] Layout Reflow & thrashing
点击右上角即可分享
微信分享提示