### Installing typed-inject with npm (Shell) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Provides the command to install the typed-inject library using the npm package manager. This is the standard way to add the library to a Node.js/TypeScript project. ```Shell npm i typed-inject ``` -------------------------------- ### Installing typed-inject with yarn (Shell) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Provides the command to install the typed-inject library using the yarn package manager. This is an alternative method to npm for adding the library to a project. ```Shell yarn add typed-inject ``` -------------------------------- ### Decorating Dependencies with typed-inject (TypeScript) Source: https://github.com/nicojs/typed-inject/blob/master/README.md This example shows how to apply the decorator pattern using `typed-inject`. It defines a base class `Foo` and a factory function `fooDecorator` that wraps the `Foo` instance. By providing the decorator factory *after* the original class with the same token ('foo'), `typed-inject` uses the factory to create the final instance, effectively decorating the original. It then resolves and uses the decorated instance. ```ts import { createInjector } from 'typed-inject'; class Foo { public bar() { console.log('bar!'); } } function fooDecorator(foo: Foo) { return { bar() { console.log('before call'); foo.bar(); console.log('after call'); }, }; } fooDecorator.inject = ['foo'] as const; const fooProvider = createInjector() .provideClass('foo', Foo) .provideFactory('foo', fooDecorator); const foo = fooProvider.resolve('foo'); foo.bar(); // => "before call" // => "bar!" // => "after call" ``` -------------------------------- ### Catching and Inspecting InjectionError in TypeScript Source: https://github.com/nicojs/typed-inject/blob/master/README.md This example demonstrates how to catch an InjectionError, check its type, and access its 'path' and 'cause' properties to understand the origin and reason for the injection failure. ```typescript const explosion = new Error('boom!'); class Boom { constructor() { throw explosion; } } class Prison { constructor(public readonly child: Boom) {} public static inject = ['boom'] as const; } try { rootInjector.provideClass('boom', Boom).injectClass(Prison); } catch (error) { if (error instanceof InjectionError) { error.path[0] === Prison; error.path[1] === 'boom'; error.path[2] === Boom; error.cause === explosion; } } ``` -------------------------------- ### Compile-time Error Handling in typed-inject (TypeScript) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Illustrates the type safety features of typed-inject by showing examples of compile-time errors. It demonstrates errors that occur when the static inject property is missing or when the order of dependencies in the inject array does not match the constructor parameters. ```TypeScript import { createInjector } from 'typed-inject'; // Same logger as before class HttpClient { constructor(private log: Logger) {} // ERROR! Property 'inject' is missing in type 'typeof HttpClient' but required } class MyService { constructor( private http: HttpClient, private log: Logger, ) {} public static inject = ['logger', 'httpClient'] as const; // ERROR! Types of parameters 'http' and 'args_0' are incompatible } const appInjector = createInjector() .provideValue('logger', logger) .provideClass('httpClient', HttpClient); const myService = appInjector.injectClass(MyService); ``` -------------------------------- ### Basic Dependency Injection with typed-inject (TypeScript) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Demonstrates the core usage of typed-inject. It shows how to define dependencies using provideValue and provideClass, and how to resolve and inject a class using injectClass, relying on the static inject property for dependency resolution. ```TypeScript import { createInjector } from 'typed-inject'; interface Logger { info(message: string): void; } const logger: Logger = { info(message: string) { console.log(message); }, }; class HttpClient { constructor(private log: Logger) {} public static inject = ['logger'] as const; } class MyService { constructor( private http: HttpClient, private log: Logger, ) {} public static inject = ['httpClient', 'logger'] as const; } const appInjector = createInjector() .provideValue('logger', logger) .provideClass('httpClient', HttpClient); const myService = appInjector.injectClass(MyService); // Dependencies for MyService validated and injected ``` -------------------------------- ### Manual Dependency Resolution and Class Instantiation (TypeScript) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Illustrates the manual process of resolving dependencies (logger, httpClient) from an injector and then manually instantiating a class (MyService) using the resolved values. This is shown as an equivalent operation to injector.injectClass. ```TypeScript const logger = appInjector.resolve('logger'); const httpClient = appInjector.resolve('httpClient'); const service = new MyService(httpClient, logger); ``` -------------------------------- ### Demonstrating Dependency Scopes (Singleton vs Transient) in typed-inject Source: https://github.com/nicojs/typed-inject/blob/master/README.md This snippet demonstrates how to use `Scope.Transient` for a factory-provided dependency (`log`) and `Scope.Singleton` for a class-provided dependency (`foo`) in `typed-inject`. It shows that resolving a `Singleton` dependency multiple times returns the same instance, while resolving a `Transient` dependency always returns a new instance. ```typescript function loggerFactory(target: Function | null) { return getLogger((target && target.name) || 'UNKNOWN'); } loggerFactory.inject = ['target'] as const; class Foo { constructor(public log: Logger) { log.info('Foo created'); } static inject = ['log'] as const; } const fooProvider = injector .provideFactory('log', loggerFactory, Scope.Transient) .provideClass('foo', Foo, Scope.Singleton); const foo = fooProvider.resolve('foo'); const fooCopy = fooProvider.resolve('foo'); const log = fooProvider.resolve('log'); console.log(foo === fooCopy); // => true console.log(log === foo.log); // => false ``` -------------------------------- ### Demonstrating Injection Error Path in Typed Inject (TypeScript) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Shows a scenario where a dependency's constructor throws an error during injection. The code defines classes with dependencies and uses createInjector to attempt injection, illustrating the detailed error path provided by typed-inject when an error occurs. ```TypeScript class GrandChild { public baz = 'baz'; constructor() { throw expectedCause; } } class Child { public bar = 'foo'; constructor(public grandchild: GrandChild) {} public static inject = ['grandChild'] as const; } class Parent { constructor(public readonly child: Child) {} public static inject = ['child'] as const; } createInjector() .provideClass('grandChild', GrandChild) .provideClass('child', Child) .injectClass(Parent); // => Error: Could not inject [class Parent] -> [token "child"] -> [class Child] -> [token "grandChild"] -> [class GrandChild]. Cause: Expected error ``` -------------------------------- ### Using injector.injectClass for Class Instantiation (TypeScript) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Shows the usage of the injector.injectClass method to automatically resolve dependencies and instantiate a class (Foo) based on its static inject property. Highlights that dependency graph issues result in compiler errors. ```TypeScript class Foo { constructor(bar: number) {} static inject = ['bar'] as const; } const foo /*: Foo*/ = injector.injectClass(Foo); ``` -------------------------------- ### Handling Async Dispose Methods with typed-inject (TS) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Shows how to define a `dispose` method that returns a `Promise` for asynchronous cleanup operations and how to properly handle the asynchronous nature when calling the injector's `dispose` method using `await` or `.then()`/`.catch()`. ```typescript import { createInjector, Disposable } from 'typed-inject'; class Foo implements Disposable { dispose(): Promise { return Promise.resolve(); } } const rootInjector = createInjector(); const fooProvider = rootInjector .provideClass('foo', Foo); const foo = fooProvider.resolve('foo'); async function disposeFoo() { await fooProvider.dispose(); } disposeFoo() .then(() => console.log('Foo disposed')) .catch(err => console.error('Foo disposal resulted in an error', err)); ``` -------------------------------- ### Using injector.resolve for Manual Token Resolution (TypeScript) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Demonstrates the direct use of the injector.resolve method to retrieve a value associated with a specific token ('foo'). It also shows an equivalent operation using injectFunction for comparison. ```TypeScript const foo = injector.resolve('foo'); // Equivalent to: function retrieveFoo(foo: number) { return foo; } retrieveFoo.inject = ['foo'] as const; const foo2 = injector.injectFunction(retrieveFoo); ``` -------------------------------- ### Using injector.provideValue to Create Child Injector (TypeScript) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Shows how to use the injector.provideValue method to create a new child injector. The child injector inherits all capabilities from the parent and additionally provides a specific value (42) for a given token ('foo'). ```TypeScript const fooInjector = injector.provideValue('foo', 42); ``` -------------------------------- ### Creating Child Injectors and Providing Dependencies with typed-inject (TypeScript) Source: https://github.com/nicojs/typed-inject/blob/master/README.md This snippet illustrates how to create a child injector using `createInjector` and chain `provideValue`, `provideFactory`, and `provideClass` methods to register dependencies. It shows how a factory function and a class can declare their dependencies using a static `inject` property. Finally, it demonstrates injecting dependencies into a function using `injectFunction`. ```ts import { createInjector } from 'typed-inject'; function barFactory(foo: number) { return foo + 1; } barFactory.inject = ['foo'] as const; class Baz { constructor(bar: number) { console.log(`bar is: ${bar}`); } static inject = ['bar'] as const; } // Create 3 child injectors here const childInjector = createInjector() .provideValue('foo', 42) // child injector can provide 'foo' .provideFactory('bar', barFactory) // child injector can provide both 'bar' and 'foo' .provideClass('baz', Baz); // child injector can provide 'baz', 'bar' and 'foo' // Now use it here function run(baz: Baz) { // baz is created! } run.inject = ['baz'] as const; childInjector.injectFunction(run); ``` -------------------------------- ### Providing Factory with Scope in typed-inject (TypeScript) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Demonstrates how to use injector.provideFactory to create a child injector that provides a value from a factory function. Shows how to inject dependencies into the factory and configure the scope (e.g., Scope.Transient) for the provided value. ```TypeScript const fooInjector = injector.provideFactory('foo', () => 42); function loggerFactory(target: Function | undefined) { return new Logger((target && target.name) || ''); } loggerFactory.inject = [TARGET_TOKEN] as const; const fooBarInjector = fooInjector.provideFactory( 'logger', loggerFactory, Scope.Transient, ); ``` -------------------------------- ### Disposing Provided Instance with typed-inject (TS) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Demonstrates the basic disposal process for a provided class instance by calling the injector's `dispose` method. Shows how a class with a `dispose` method is cleaned up and that the injector becomes unusable after disposal. ```typescript import { createInjector } from 'typed-inject'; class Foo { constructor() { console.log('Foo created'); } dispose() { console.log('Foo disposed'); } } const rootInjector = createInjector(); const fooProvider = rootInjector.provideClass('foo', Foo); fooProvider.resolve('foo'); // => "Foo created" await rootInjector.dispose(); // => "Foo disposed" fooProvider.resolve('foo'); // Error: Injector already disposed ``` -------------------------------- ### Manual Dependency Resolution and Function Invocation (TypeScript) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Illustrates the manual process of resolving dependencies (logger, httpClient) from an injector and then manually invoking a function (doRequest) using the resolved values. This is shown as an equivalent operation to injector.injectFunction. ```TypeScript const logger = appInjector.resolve('logger'); const httpClient = appInjector.resolve('httpClient'); const request = doRequest(httpClient, logger); ``` -------------------------------- ### Handling Injection Errors and Accessing Cause in Typed Inject (TypeScript) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Demonstrates how to catch InjectionError when injection fails. It shows how to import InjectionError and access the original error's cause property for detailed debugging information, such as the stack trace. ```TypeScript import { InjectionError } from 'typed-inject'; try { createInjector() .provideClass('grandChild', GrandChild) .provideClass('child', Child) .injectClass(Parent); } catch (err) { if (err instanceof InjectionError) { console.error(err.cause.stack); } } ``` -------------------------------- ### Understanding Disposal Order in typed-inject (TS) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Illustrates the order in which provided instances are disposed when an injector is disposed. Instances are disposed in the reverse order of their provision (child-first), similar to a stack. ```typescript import { createInjector } from 'typed-inject'; class Foo { dispose() { console.log('Foo disposed'); } } class Bar { dispose() { console.log('Bar disposed'); } } class Baz { static inject = ['foo', 'bar'] as const; constructor( public foo: Foo, public bar: Bar, ) {} } const rootInjector = createInjector(); rootInjector.provideClass('foo', Foo).provideClass('bar', Bar).injectClass(Baz); await rootInjector.dispose(); // => "Foo disposed" // => "Bar disposed", ``` -------------------------------- ### Using tokens Helper for Inject Array in typed-inject (TypeScript) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Shows how to use the tokens helper function as a concise way to define the inject array for injectable classes or functions. Explains that it's equivalent to using a readonly tuple with as const. ```TypeScript const inject = tokens('foo', 'bar'); // Equivalent to: const inject = ['foo', 'bar'] as const; ``` -------------------------------- ### Creating and Disposing Child Injector Scope in typed-inject (TypeScript) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Illustrates the use of injector.createChildInjector to create a new, disposable scope for handling tasks. Shows how to provide classes within the child scope and properly dispose of the scope and its dependencies using scope.dispose(). ```TypeScript const parentInjector = createInjector().provideValue('foo', 'bar'); for (const task of tasks) { try { const scope = parentInjector.createChildInjector(); const foo = scope.provideClass('baz', DisposableBaz).injectClass(Foo); foo.handle(task); } finally { await scope.dispose(); // Dispose the scope, including instances of DisposableBaz // Next task gets a fresh scope } } ``` -------------------------------- ### Implementing Disposable Interface in typed-inject (TS) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Illustrates the use of the `Disposable` interface provided by `typed-inject` as a convenience for marking classes that have a `dispose` method, improving type safety and code clarity. ```typescript import { Disposable } from 'typed-inject'; class Foo implements Disposable { dispose() {} } ``` -------------------------------- ### Using injector.injectFunction for Function Invocation (TypeScript) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Shows the usage of the injector.injectFunction method to automatically resolve dependencies and invoke a function (foo) based on its inject property. Highlights that dependency graph issues result in compiler errors. ```TypeScript function foo(bar: number) { return bar + 1; } foo.inject = ['bar'] as const; const baz /*: number*/ = injector.injectFunction(Foo); ``` -------------------------------- ### Injecting Magic Tokens in typed-inject (TS) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Shows how to inject the built-in magic tokens `INJECTOR_TOKEN` (providing the current injector instance) and `TARGET_TOKEN` (providing the class or function being injected into) into a class constructor using the `static inject` property. ```typescript import { createInjector, Injector, TARGET_TOKEN, INJECTOR_TOKEN, } from 'typed-inject'; class Foo { constructor(injector: Injector<{}>, target: Function | undefined) {} static inject = [INJECTOR_TOKEN, TARGET_TOKEN] as const; } const foo = createInjector().inject(Foo); ``` -------------------------------- ### Disposing Child Injectors Automatically with typed-inject (TS) Source: https://github.com/nicojs/typed-inject/blob/master/README.md Demonstrates that disposing a parent injector automatically triggers the disposal of all child injectors created from it, ensuring a cascading cleanup process from the top down. ```typescript import { createInjector } from 'typed-inject'; class Foo {} class Bar {} const rootInjector = createInjector(); const fooProvider = rootInjector.provideClass('foo', Foo); const barProvider = fooProvider.provideClass('bar', Bar); await rootInjector.dispose(); // => fooProvider is also disposed! fooProvider.resolve('foo'); // => Error: Injector already disposed ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.