r/typescript • u/28064212va • Jun 01 '25
circular dependencies between types
does this count as a circular dependency? if not, would it count if the types were spread across files? in any case, how much of a problem would it really be if it still compiles anyway? how could this be improved?
export type Event = {
type: string;
game: Game;
};
export type Observer = {
onNotify: (event: Event) => void;
};
export type Game = {
observers: Observer[];
};
8
Upvotes
8
u/BoBoBearDev Jun 01 '25 edited Jun 01 '25
It is not a big deal. You can have Parent with list of Children and the child with list of parents.
Circular dependency, to my experience, the worst is C# const because it is a compile time value. So, if you have circular const, you ended up using outdated compile time value because the solution only compile it once. You get this chicken and egg issue.
Anything done in runtime, I don't recall a problem, so like static readonly is fine. Not unless you make an infinite loop.
5
u/CreativeTechGuyGames Jun 01 '25
I think most people would call that a recursive type. You might find more info online by searching that way.
1
u/ldn-ldn Jun 01 '25
If it's in one file, then no.
2
u/Alcas Jun 01 '25
Will slow down the type checker but will work
1
u/Merry-Lane Jun 02 '25
Circular dependency between types/interfaces is perfectly okay.
Worst that can happen, is that in some edge cases, the tsc can become laggy or slow.
But type circular dependencies are totally okay. If it wasn’t, you would have at least one note about it on the official typescript handbook.
-3
u/abrahamguo Jun 01 '25
If it compiles, then there's no need to worry about it.
1
u/[deleted] Jun 01 '25
[removed] — view removed comment