Created
May 16, 2025 03:23
-
-
Save audinue/d464e2445825e793ed65f21366b8e0d8 to your computer and use it in GitHub Desktop.
Immutable type safe dependency container for TypeScript
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
class DependencyContainer<T> { | |
constructor( | |
private factories: Record<string, (self: any) => any> = {}, | |
private objects: Record<string, any> = {} | |
) {} | |
set<K extends keyof T | (string & {}), V>( | |
key: K, | |
factory: (self: DependencyContainer<T>) => V | |
): DependencyContainer<T & { [P in K]: V }> { | |
return new DependencyContainer({ ...this.factories, [key]: factory }); | |
} | |
get<K extends keyof T>(key: K): T[K] { | |
let object = this.objects[key as any]; | |
if (!object) { | |
object = this.factories[key as any](this); | |
this.objects[key as any] = object; | |
} | |
return object; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment