TypeScriptModules and namespaces
Circular dependencies between modules in TypeScript
5 Two modules that import each other
hardWrite two modules that each import from the other, creating a circular dependency. Show what works, what breaks, and how to avoid the problem.
Stuck? Three hints, smallest first
- 1. Circular imports of types are completely fine, because types are erased.
- 2. Circular imports of values work only if nothing is used while the modules are still loading.
- 3. The reliable fix is a third module holding whatever both need.
The real answer, across 2 files. Type-checked by the compiler at build time; not runnable in a browser, because a panel cannot contain import or export.
import type { Trip } from './trip.js';
export class Bus {
constructor(public plate: string) {}
// A type-only reference to Trip. Erased, so no runtime cycle at all.
describeTrip(trip: Trip): string {
return `${this.plate} runs ${trip.route}`;
}
}
import { Bus } from './bus.js';
export class Trip {
constructor(public route: string, public bus: Bus) {}
describe(): string {
// Called later, long after both modules have finished loading, so the
// value-level cycle is harmless here.
return this.bus.describeTrip(this);
}
}
// This, by contrast, would run DURING loading and is where cycles bite:
// export const EAGER = new Bus('LAG-441-XA').plate;
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
// The runnable version, which also shows the fix: no cycle at all, because
// the shared shape lives on its own and neither side reaches back.
// What both sides agree on, and what a third module would hold.
interface HasRoute { route: string }
class Bus {
constructor(public plate: string) {}
describeTrip(trip: HasRoute): string {
return `${this.plate} runs ${trip.route}`;
}
}
class Trip implements HasRoute {
constructor(public route: string, public bus: Bus) {}
describe(): string {
return this.bus.describeTrip(this);
}
}
const bus = new Bus('LAG-441-XA');
const trip = new Trip('Lagos - Abuja', bus);
console.log(trip.describe());
console.log(bus.describeTrip({ route: 'Lagos - Kano' }));
// Why eager use during loading is the real danger, in miniature:
// if this ran while the other module was still initialising, `later` would
// still be undefined and the call would throw.
let later: ((s: string) => string) | undefined;
const tooEarly = typeof later === 'function' ? later('x') : 'not ready yet';
later = (s) => `ready: ${s}`;
console.log('during loading:', tooEarly);
console.log('after loading :', later('x'));
test('the trip describes itself through the bus', trip.describe(), 'LAG-441-XA runs Lagos - Abuja');
test('the bus accepts anything with a route', bus.describeTrip({ route: 'Lagos - Kano' }), 'LAG-441-XA runs Lagos - Kano');
test('using a value too early gives nothing', tooEarly, 'not ready yet');
test('the same call works once loading finished', later('x'), 'ready: x');
test('Trip satisfies the shared shape', trip.route, 'Lagos - Abuja');
Output
The distinction that resolves most circular-import confusion: import type can never cause a cycle, because it is erased before the JavaScript exists. Cycles only bite when a value is used while the modules are still loading, as the commented EAGER line would be. The runnable block shows the durable fix — put the shared shape somewhere neither side has to import the other for.