DI(Dependency Injection) in TypeScript


You can use “dependency injection" with inversify.



npm install inversify reflect-metadata --save

Then you need to set up the following for using Decorators.

    "compilerOptions": {
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true

Abstract class in TypeScript

You should use abstraction class. The most popular way to abstract class is “Interface", but “Abstract class" is used in TypeScript.

import 'reflect-metadata';
import {injectable, inject} from 'inversify';

export default abstract class BaseHoge {
	abstract test(): string

export default class Hoge extends BaseHoge {
    constructor(private fuga: BaseFuga) {

    test(): string {
    	return this.fuga.getTest()

export default abstract class BaseFuga {
	abstract getTest(): string

export default class Fuga extends BaseFuga {
    getTest(): string {
    	return 'test'

Create the DI Container

You inject with DI container.

import 'reflect-metadata';
import { Container, injectable, inject } from "inversify";

import BaseHoge from "./BaseHoge";
import BaseFuga from "./BaseFuga";
import Hoge from "./Hoge";
import Fuga from "./Fuga";

export default class Kernel {

    container: Container

    constructor() {

    declareDependencies (): void {
        this.container = new Container();

    get(serviceIdentifier): T {
        return this.container.get(serviceIdentifier)

How to call DI Container. it should DI Kernel class?

const hoge: BaseHoge = new Kernel().get(BaseHoge);