Topological Sort 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
- ✓Topological Sort runs in O(V+E) time and O(V) space, in TypeScript as in every other language.
- ✓The same runtime story as JavaScript, plus generics that let a single topoOrder<T>(graph: ReadonlyMap<T, readonly T[]>) function be reused across every node type the codebase has, with Map<T, number> for indegree so T need not be a string.
- ✓Type the adjacency structure as ReadonlyMap<T, readonly T[]> so the compiler rejects any code path that tries to mutate the graph mid-sort, and keep the same index-pointer-not-.shift() discipline as plain JavaScript, the type layer fixes the shape of the queue, not its performance.
- ✓The TypeScript trap: Map<T, number> uses reference equality for object keys, so if T is an object type and two logically-equal nodes are actually two different object instances (a common shape when nodes are deserialized from JSON twice, or reconstructed rather than looked up), the indegree map silently treats them as two different keys, TypeScript's structural typing gives no compile-time warning here, because from the type checker's point of view both objects satisfy T equally well.
- ✓Identical to JavaScript at runtime, since the compiler erases every type annotation before emitting the array and Map operations that actually run; the const type parameters and conditional-type machinery you might add to make the generic signature precise cost real time in tsc, invisible at runtime but a real, measurable addition to build time on a large enough codebase.
What Topological Sort actually is
Topological Sort in TypeScript: what you actually reach for
TypeScript implementation
function topoOrder<T>(graph: ReadonlyMap<T, readonly T[]>): T[] {
const indegree = new Map<T, number>();
for (const node of graph.keys()) indegree.set(node, 0);
for (const nexts of graph.values()) {
for (const n of nexts) indegree.set(n, (indegree.get(n) ?? 0) + 1);
}
const queue: T[] = [];
for (const [node, deg] of indegree) if (deg === 0) queue.push(node);
let head = 0; // index pointer: never .shift()
const order: T[] = [];
while (head < queue.length) {
const node = queue[head++]!;
order.push(node);
for (const next of graph.get(node) ?? []) {
const d = indegree.get(next)! - 1;
indegree.set(next, d);
if (d === 0) queue.push(next);
}
}
if (order.length !== indegree.size) {
throw new Error("not a DAG: cycle present");
}
return order;
}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 Topological Sort?
The same runtime story as JavaScript, plus generics that let a single topoOrder<T>(graph: ReadonlyMap<T, readonly T[]>) function be reused across every node type the codebase has, with Map<T, number> for indegree so T need not be a string.
What is the most common TypeScript mistake when implementing Topological Sort?
Map<T, number> uses reference equality for object keys, so if T is an object type and two logically-equal nodes are actually two different object instances (a common shape when nodes are deserialized from JSON twice, or reconstructed rather than looked up), the indegree map silently treats them as two different keys, TypeScript's structural typing gives no compile-time warning here, because from the type checker's point of view both objects satisfy T equally well.
How does Topological Sort actually perform in TypeScript?
Identical to JavaScript at runtime, since the compiler erases every type annotation before emitting the array and Map operations that actually run; the const type parameters and conditional-type machinery you might add to make the generic signature precise cost real time in tsc, invisible at runtime but a real, measurable addition to build time on a large enough codebase. 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? Student discounts on developer tools are collected on Noizz, tool by tool.
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.