w3resource

TypeScript Circular Dependencies

TypeScript Modules and Namespaces : Exercise-5 with Solution

Write two TypeScript modules that import from each other, creating a circular dependency. Show how TypeScript handles circular dependencies and uses the imported functions or classes.

Sample Solution:

TypeScript Code:

main.ts

import { sayHelloFromA } from './test_module_a';
sayHelloFromA();

test_module_a.ts

import { sayHelloFromB } from './test_module_b';
export function sayHelloFromA() {
  console.log('Hello from module A');
  sayHelloFromB();
}

test_module_b.ts

import { sayHelloFromA } from './test_module_a';
export function sayHelloFromB() {
  console.log('Hello from module B');
}

Output:

Hello from module A
Hello from module B

TypeScript Editor:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.


Previous: TypeScript Default Export.
Next: TypeScript Basic Namespace.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.