Created
March 20, 2024 01:51
-
-
Save joemaffei/fec921db12f5a311eea94a2b2d007c9f to your computer and use it in GitHub Desktop.
Stupid simple dependency injection 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
/** | |
* Module-level variable where all of the global dependency injection | |
* overrides are stored. | |
*/ | |
const provisions = new Map<unknown, unknown>(); | |
/** | |
* Adds an override to the global dependency injection context. | |
* TypeScript ensures that the signature of the override is the same | |
* as that of the dependency being overridden. | |
* | |
* There are probably dozens of TypeScript caveats to account for, | |
* but this is just to illustrate that it can be done easily. | |
* | |
* This is similar to Angular's `@Injectable({ providedIn: 'root' })`. | |
* @see https://angular.io/guide/providers | |
*/ | |
export function provide<T>(token: T, override: T) { | |
provisions.set(token, override); | |
} | |
/** | |
* Returns the provided dependency for the respective token, if provided. | |
* If not, it returns the dependency itself. | |
* This is very similar to how Angular's inject function works. | |
* @see https://angular.io/api/core/inject | |
*/ | |
export function inject<T>(token: T) { | |
return provisions.has(token) ? (provisions.get(token) as T) : token; | |
} |
Author
joemaffei
commented
Mar 20, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment