Typed Inject

5.0.0 · active · verified Sun Apr 19

Typed Inject is a robust, 100% type-safe dependency injection framework specifically designed for TypeScript applications. It allows developers to inject classes, interfaces, or primitive values, leveraging TypeScript's type system to ensure that if a project compiles, its dependencies are correctly resolved at runtime with their declared types. The current stable version is 5.0.0, released in late 2024. Major versions typically roll out with significant changes like Node.js version updates or module system migrations, as seen with the v4.0.0 (ESM migration) and v5.0.0 (Node 16 drop) releases. Its primary differentiator is its strong type-safety, which virtually eliminates runtime dependency resolution errors by shifting validation to compile time. It handles various injection patterns, including class, value, and factory providers, and supports concepts like child injectors and lifecycle control.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `typed-inject` by creating an injector, providing a value and a class, and then injecting a service that depends on both.

import { createInjector } from 'typed-inject';

interface Logger {
  info(message: string): void;
}

const logger: Logger = {
  info(message: string) {
    console.log(`[Logger]: ${message}`);
  },
};

class HttpClient {
  constructor(private log: Logger) {}
  public static inject = ['logger'] as const;

  fetchData(url: string) {
    this.log.info(`Fetching data from ${url}`);
    return Promise.resolve(`Data from ${url}`);
  }
}

class MyService {
  constructor(
    private http: HttpClient,
    private log: Logger,
  ) {}
  public static inject = ['httpClient', 'logger'] as const;

  async doSomething() {
    this.log.info('MyService doing something...');
    const data = await this.http.fetchData('https://example.com/api/data');
    this.log.info(`Received: ${data}`);
    return data;
  }
}

const appInjector = createInjector()
  .provideValue('logger', logger)
  .provideClass('httpClient', HttpClient);

// Create an instance of MyService with all dependencies resolved
const myService = appInjector.injectClass(MyService);

myService.doSomething();
// This demonstrates setting up an injector, providing a value and a class, and then injecting a dependent class.

view raw JSON →