TypeDI
Search…
Getting Started
It's possible to use TypeDI without TypesScript, however some of the functionality is limited or not available. These differences are listed below in the Limitations section.

Installation

To start using TypeDI with JavaScript install the required packages via NPM:
1
npm install typedi reflect-metadata
Copied!

Basic usage

The most basic usage is to request an instance of a class definition. TypeDI will check if an instance of the class has been created before and return the cached version or it will create a new instance, cache and return it.
1
import 'reflect-metadata';
2
import { Container } from 'typedi';
3
4
class ExampleClass {
5
print() {
6
console.log('I am alive!');
7
}
8
}
9
10
/** Register this class to the TypeDI container */
11
Container.set({ id: ExampleClass, type: ExampleClass });
12
13
/** Request an instance of ExampleClass from TypeDI. */
14
const classInstance = Container.get(ExampleClass);
15
16
/** We received an instance of ExampleClass and ready to work with it. */
17
classInstance.print();
Copied!
For more advanced usage examples and patterns please read the next page.

Limitations

When registering your dependencies with the Container.set() method, there are three options available that must be set. Either one of the following are allowed: type, factory, or value but not more than one.
  • Container.set({ id: ExampleClass, type: ExampleClass});
  • Container.set({ id: ExampleClass, value: new ExampleClass});
  • Container.set({ id: ExampleClass, factory: ExampleClass});
To get started quickly, it is recommend to use type due to the fact that using value will instantiate the class before it's registered to the TypeDI Container. Using type will also assure that the TypeDI Container is injected to the constructor.