TypeScript Compiler API

Node.getChildren()

Returns syntactic children including token nodes and syntax-list wrappers that forEachChild generally omits. Useful for token-aware inspection; for structural traversal prefer forEachChild. Use the matching parsed SourceFile, not an unrelated or stale tree. Baseline: TypeScript 5.8.3; run locally with Node.js, not as a ByteMind CodeRunner exercise.

Formal Syntax & Structure

typescript syntaxtypescript
node.getChildren(sourceFile?: ts.SourceFile): readonly ts.Node[]

Parameters & Attributes

NameTypeDescription
sourceFilets.SourceFileMatching source file for token positions.

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");function parse(text) {  return ts.createSourceFile("input.ts", text, ts.ScriptTarget.ES2022, true, ts.ScriptKind.TS);}const f=parse("const x = 1;"); const d=f.statements[0].declarationList.declarations[0];const children=d.getChildren(f); const structural=[]; ts.forEachChild(d,n=>{structural.push(n.kind);});assert(children.some(n=>n.kind===ts.SyntaxKind.EqualsToken)); assert(!structural.includes(ts.SyntaxKind.EqualsToken));assert(children.some(n=>ts.isIdentifier(n))); console.log("getChildren includes equals token; forEachChild omits it");
// Run: node example.cjs// Expected stdout: getChildren includes equals token; forEachChild omits it
TypeScript Reference