Skip to content

Instantly share code, notes, and snippets.

@tanvirraj
Created March 17, 2023 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanvirraj/d246396b69ebedb84761e51db743f4b6 to your computer and use it in GitHub Desktop.
Save tanvirraj/d246396b69ebedb84761e51db743f4b6 to your computer and use it in GitHub Desktop.
dependency injection typescript example with classes this file is generated by chatGPT

First, create an interface for the dependency you want to inject, for example:

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

Next, create a class that implements the interface:

class ConsoleLogger implements Logger {
  log(message: string): void {
    console.log(message);
  }
}

Now, create a class that depends on the Logger interface:

class MyClass {
  private logger: Logger;

  constructor(logger: Logger) {
    this.logger = logger;
  }

  doSomething(): void {
    this.logger.log('Doing something...');
  }
}

Finally, create an instance of the Logger implementation and pass it to the constructor of the class that depends on it:

const logger = new ConsoleLogger();
const myClass = new MyClass(logger);
myClass.doSomething();

This example demonstrates how Dependency Injection can be implemented in TypeScript using classes. By using interfaces to define dependencies, you can easily swap out implementations without changing the code that depends on them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment