How do circular module dependencies in TypeScript behave differently depending on whether the compiled output targets CommonJS or ES Modules?
Short answer
The underlying circular-dependency behavior is inherited directly from the target JavaScript module system's own semantics (partially-initialized exports at the moment of the cycle) — TypeScript's type system itself doesn't change this runtime behavior, though its static…
Advertisement
AModel answer
The underlying circular-dependency behavior is inherited directly from the target JavaScript module system's own semantics (partially-initialized exports at the moment of the cycle) — TypeScript's type system itself doesn't change this runtime behavior, though its static analysis can sometimes make circularly-typed interfaces work at the type level even when runtime values would be problematic.
// a.ts
import { b } from './b';
export const a = 'A';
console.log(b); // may be undefined at this point due to the cycle, regardless of TS
// b.ts
import { a } from './a';
export const b = 'B';Real-world example
Debugging a circular-import-caused undefined value bug that TypeScript's type checker didn't (and structurally couldn't) catch.
Likely follow-ups
- Why can't TypeScript's static type checker fully prevent this class of runtime circular-dependency bug?
Related topics