Cycle Detection Implementation in TypeScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Cycle Detection runs in O(V+E) time and O(V) space, in TypeScript as in every other language.
- ✓Same runtime primitives as JavaScript, Map, Set, arrays, plus a type layer to model the three states as a real enum (enum State { White, Gray, Black }) instead of magic numbers, and generic signatures like ReadonlyMap<T, readonly T[]> to express that the algorithm must not mutate the graph it is given.
- ✓Model state with an actual enum, not string literals compared with ===, so a typo in a state name is a compile error rather than a silently-false comparison, and use a switch over the enum with an exhaustiveness check (a default branch assigning to a variable typed never) so adding a fourth state later is a compile error everywhere it is unhandled, not a runtime bug discovered in production.
- ✓The TypeScript trap: If node state is stored as Record<T, State> instead of Map<T, State>, reading a key that was never set gives you State | undefined at the value level but plain State at the type level unless the compiler flag noUncheckedIndexedAccess is enabled, without that flag, an uninitialized node's state compares as not-equal to every real enum member (because it is actually undefined), the traversal silently treats it as unvisited, and a real cycle through that node can go undetected instead of surfacing as a type error you would have caught at compile time.
- ✓Identical to JavaScript at runtime, the type annotations are erased entirely by the compiler, so a tsc-compiled DFS runs exactly the same bytecode as the equivalent hand-written JavaScript.
What Cycle Detection actually is
Cycle Detection in TypeScript: what you actually reach for
TypeScript implementation
enum State { White, Gray, Black }
type Graph<T> = ReadonlyMap<T, readonly T[]>;
function hasCycle<T>(graph: Graph<T>): boolean {
const state = new Map<T, State>();
for (const node of graph.keys()) state.set(node, State.White);
for (const start of graph.keys()) {
if (state.get(start) !== State.White) continue;
const stack: Array<[T, number]> = [[start, 0]];
state.set(start, State.Gray);
while (stack.length > 0) {
const frame = stack[stack.length - 1]!;
const [node, i] = frame;
const children = graph.get(node) ?? [];
if (i < children.length) {
frame[1] += 1;
const child = children[i]!;
const s = state.get(child); // Map read: `undefined` is a real possibility
if (s === State.Gray) return true;
if (s === undefined || s === State.White) {
state.set(child, State.Gray);
stack.push([child, 0]);
}
} else {
state.set(node, State.Black);
stack.pop();
}
}
}
return false;
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(V+E)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Cycle Detection?
Same runtime primitives as JavaScript, Map, Set, arrays, plus a type layer to model the three states as a real enum (enum State { White, Gray, Black }) instead of magic numbers, and generic signatures like ReadonlyMap<T, readonly T[]> to express that the algorithm must not mutate the graph it is given.
What is the most common TypeScript mistake when implementing Cycle Detection?
If node state is stored as Record<T, State> instead of Map<T, State>, reading a key that was never set gives you State | undefined at the value level but plain State at the type level unless the compiler flag noUncheckedIndexedAccess is enabled, without that flag, an uninitialized node's state compares as not-equal to every real enum member (because it is actually undefined), the traversal silently treats it as unvisited, and a real cycle through that node can go undetected instead of surfacing as a type error you would have caught at compile time.
How does Cycle Detection actually perform in TypeScript?
Identical to JavaScript at runtime, the type annotations are erased entirely by the compiler, so a tsc-compiled DFS runs exactly the same bytecode as the equivalent hand-written JavaScript. The cost TypeScript adds is at compile time: a deeply generic Graph<T> signature combined with conditional types over the node type can noticeably slow tsc on a large codebase, invisible to the running program but very visible in CI build times. Time complexity is O(V+E) and space is O(V).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.