npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@snap/ts-inject

v0.2.0

Published

100% typesafe dependency injection framework for TypeScript projects

Downloads

64

Readme

ts-inject

ts-inject is a 100% typesafe dependency injection framework for TypeScript projects, designed to enhance code sharing and modularity by ensuring compile-time dependency resolution. This framework leverages the dependency injection design pattern to decouple dependency usage from creation, allowing components to rely on interfaces rather than implementations.

Features and Alternatives

ts-inject brings typesafety to dependency injection, setting it apart from a vast majority of frameworks, like InversifyJS, which operate at runtime and therefore lack this level of typesafety.

While typed-inject also prioritizes typesafety, it lacks several key features that ts-inject offers:

  • Overcomes TypeScript Nested Type Limitations: Unlike some frameworks, ts-inject navigates around TypeScript's limits on nested types, making it more robust for complex applications.
  • Composable Containers: ts-inject enables merging multiple containers, facilitating greater modularity and code reuse.
  • PartialContainer: It allows service registration without pre-defined dependencies, offering more flexibility compared to regular containers.

Getting Started

Installation

npm install @snap/ts-inject

Sample Usage

This quick start guide demonstrates how to define services, register them in a container, and then retrieve them for use.

Defining Services

Define a couple of services. For simplicity, we'll use a Logger service and a Database service, where Database depends on Logger for logging purposes.

// Logger service definition
class Logger {
  log(message: string) {
    console.log(`Log: ${message}`);
  }
}

// Database service depends on Logger
class Database {
  constructor(private logger: Logger) {}

  save(record: string) {
    this.logger.log(`Saving record: ${record}`);
    // Assume record saving logic here
  }
}

Setting Up the Container

With ts-inject, you can easily set up a container to manage these services:

import { Container, Injectable } from "@snap/ts-inject";

// Define Injectable factory functions for services
const loggerFactory = Injectable("Logger", () => new Logger());
const databaseFactory = Injectable("Database", ["Logger"] as const, (logger: Logger) => new Database(logger));

// Create a container and register services
const container = Container.provides(loggerFactory).provides(databaseFactory);

// Now, retrieve the Database service from the container
const db = container.get("Database");
db.save("user1"); // Log: Saving record: user1

Composable Containers

ts-inject supports composable containers, allowing you to modularize service registration:

const baseContainer = Container.provides(loggerFactory);
const appContainer = Container.provides(baseContainer).provide(databaseFactory);

const db: Database = appContainer.get("Database");
db.save("user2"); // Log: Saving record: user2

Key Concepts

  • Container: A registry for all services, handling their creation and retrieval.
  • PartialContainer: Similar to a Container but allows services to be registered without defining all dependencies upfront. Unlike a regular Container, it does not support retrieving services directly.
  • Service: Any value or instance provided by the Container.
  • Token: A unique identifier for each service, used for registration and retrieval within the Container.
  • InjectableFunction: Functions that return service instances. They can include dependencies which are injected when the service is requested.
  • InjectableClass: Classes that can be instantiated by the Container. Dependencies should be specified in a static "dependencies" field to enable proper injection.

API Reference

For comprehensive documentation of all ts-inject features and APIs, please refer to the API Reference.

Contributing

Contributing guide.

License

ts-inject is published under MIT license.

Project Origins

ts-inject originated as an internal project at Snap Inc., developed by Weston Fribley. Inspired by the principles of typed-inject, it was designed to address the limitations of existing dependency injection frameworks and improve typesafe dependency resolution in TypeScript. Initially aimed at enhancing CameraKit's codebase, its success led to its adoption across various teams at Snap Inc., and now it has evolved into an open-source project to benefit the wider TypeScript community.