Member-only story

Dependency Injection in Node.js + TypeScript

Masoud Banimahd
3 min readJan 1, 2023

Dependency injection (DI) is a design pattern that allows a class to receive its dependencies from external sources rather than creating them itself. This can be particularly useful in large or complex applications, as it helps to decouple the different parts of the system and make it easier to test and maintain.

TypeScript is a popular programming language that is a superset of JavaScript, and it supports DI out of the box. In this blog post, we will explore how to use DI in a TypeScript application.

There are a few different ways to implement DI in TypeScript. One common approach is to use constructor injection, where dependencies are passed to a class via its constructor function. For example:

class ServiceA {
doSomething() {
console.log('Doing something');
}
}

class ServiceB {
constructor(private serviceA: ServiceA) {}

doSomethingElse() {
this.serviceA.doSomething();
console.log('Doing something else');
}
}

const serviceA = new ServiceA();
const serviceB = new ServiceB(serviceA);
serviceB.doSomethingElse();

In this example, ServiceB depends on ServiceA, and it receives an instance of ServiceA via its constructor. This allows ServiceB to use the doSomething() method of ServiceA without having to know how to create an instance of ServiceA itself.

Another way to implement DI in TypeScript is to use an inversion of control (IoC) container. An IoC container is a tool that manages the creation and injection of…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Masoud Banimahd
Masoud Banimahd

Written by Masoud Banimahd

Experienced Full-stack Engineer | NodeJS & .NET Pro | Tech Enthusiast | Knowledge Seeker - Reach me : https://masoudb.com/

Responses (2)

Write a response

Do you get autocompletion / intellisense benefits with DI ?

The container will automatically inject any dependencies that the classes require

Are you sure? because you just initialized ServiceB with an instance of ServiceA
container.set(ServiceB, new ServiceB(container.get(ServiceA)));