I just stumbled upon the circular dependency problem when building a project I am working on: a small ORM, for learning purposes.
Minimal project to reproduce the problem can be found here. Here is an even simpler overview:
Article:
import { ManyToMany } from './ManyToMany';
import { Tag } from './Tag';
export class Article {
@ManyToMany(Tag)
tags: Tag[] = [];
}
ManyToMany:
//no imports
export function ManyToMany(entity) {
…
}
Tag:
import { ManyToMany } from './ManyToMany';
import { Article } from './Article';
export class Tag {
@ManyToMany(Article)
articles: Article[] = [];
}
It is important that the code is not changed too much or at all because this affects the DX. I don't want the users of this library to create additional hacky files to fix this problem.
I found a list of discussions but none of them are elegant:
- https://medium.com/visual-development/how-to-fix-nasty-circular-dependency-issues-once-and-for-all-in-javascript-typescript-a04c987cf0de
- https://github.com/Microsoft/TypeScript/issues/20361
- Circular Type References in TypeScript
- https://spin.atomicobject.com/2018/06/25/circular-dependencies-javascript/
The best solution that I could find is using the internal module pattern. This and all other solutions are just hacks and workarounds to this problem and none actually fixes it.
Is there a better, more elegant solution to this without creating additional files or move code around?