TypeScript Compiler API
ts.visitEachChild()
Visits and reconstructs a node’s structural children using the visitor. It does not call the visitor on the parent itself; recursion is normally implemented by returning visitEachChild from the visitor. Unlike forEachChild, it returns an updated node and supports replacement or removal in legal child positions. Preserve node kinds where parent slots require them. 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.visitEachChild<T extends ts.Node>(node: T, visitor: ts.Visitor, context: ts.TransformationContext | undefined): T (common overload)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| node | T | Parent node. |
| visitor | ts.Visitor | Visitor for children. |
| context | ts.TransformationContext | undefined | Transformation context; use the supplied context in transforms. |
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 = 7 + 7;", ts.ScriptTarget.ES2022, true);const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });const replaceSeven = context => root => { function visit(node) { if (ts.isNumericLiteral(node) && node.text === "7") return context.factory.createNumericLiteral(8); return ts.visitEachChild(node, visit, context); } return ts.visitNode(root, visit, ts.isSourceFile);};const result = ts.transform(source, [replaceSeven]);try { console.log(printer.printFile(result.transformed[0]).trim()); } finally { result.dispose(); }
// Run: node example.cjs// Expected stdout: const x = 8 + 8;