TypeScript Compiler API

ts.forEachChild()

Visits structural children of one AST node in source order. Recursion is explicit; use a callback with no truthy return to visit every child. A truthy return stops traversal and is returned by the function. Unlike getChildren, this is not a token-by-token walk. Baseline: the Node.js API of TypeScript 5.8.3. The examples are CommonJS tooling scripts, not browser or CodeRunner snippets. TypeScript must be installed locally.

Formal Syntax & Structure

typescript syntaxtypescript
ts.forEachChild<T>(node, cbNode, cbNodes?): T | undefined

Parameters & Attributes

NameTypeDescription
nodets.NodeParent whose children are visited.
cbNode(node: ts.Node) => T | undefinedVisitor for a child node.
cbNodes(nodes: ts.NodeArray<ts.Node>) => T | undefinedOptional visitor for embedded node arrays.

Working Example

Example Snippettypescript
// Use a new empty directory. Install: npm install --save-exact typescript@5.8.3// File: example.cjs (omit this label)const ts = require("typescript");const assert = require("node:assert/strict");const source = ts.createSourceFile("input.ts", "const x = 1; function twice(n: number) { return n * 2; }", ts.ScriptTarget.ES2022, true);const names = [];function visit(node) {  if (ts.isIdentifier(node)) names.push(node.text);  ts.forEachChild(node, visit);}visit(source);assert.deepEqual(names, ["x", "twice", "n", "n"]);console.log(names.join(","));
// Run: node example.cjs// Expected stdout: x,twice,n,n
// Separate variation in a fresh directory.// File: example.cjs (omit this label)const ts = require("typescript");const assert = require("node:assert/strict");const source = ts.createSourceFile("input.ts", "const count = 7;", ts.ScriptTarget.ES2022, true);let calls = 0;const result = ts.forEachChild(source, () => { calls++; return "stop"; });assert.equal(calls, 1);assert.equal(result, "stop");console.log(calls, result);
// Run: node example.cjs// Expected stdout: 1 stop
TypeScript Reference