TypeScript Compiler API
ts.visitNode()
Applies a visitor to a single supplied node; recursion is controlled by the visitor. A visitor can replace or remove a node where the surrounding syntax permits. An optional type guard checks the resulting node shape; optional lifting handles arrays in single-node positions. The overloads refine the return type based on the input and guard. 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.visitNode(node, visitor, test?, lift?): ts.Node | undefined (representative overload)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| node | ts.Node | undefined | Node to visit. |
| visitor | ts.Visitor | Visitor callback. |
| test | (node: ts.Node) => boolean | Optional result-kind test. |
| lift | (nodes: readonly ts.Node[]) => ts.Node | Optional conversion of multiple results to one node. |
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 count: number = 7;", ts.ScriptTarget.ES2022, true);const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });const old = source.statements[0].declarationList.declarations[0].initializer;const next = ts.visitNode(old, n => ts.isNumericLiteral(n) ? ts.factory.createNumericLiteral(11) : n, ts.isExpression);assert(ts.isNumericLiteral(next));assert.equal(old.text, "7");console.log(printer.printNode(ts.EmitHint.Expression, next, source));
// Run: node example.cjs// Expected stdout: 11