0Pricing
TypeScript Academy · Lesson

Traversing the AST with Visitors

Walk syntax tree nodes to analyze code structure.

Traversing the AST with Visitors is a free TypeScript Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is the AST?

TypeScript parses source code into an Abstract Syntax Tree (AST) — a tree of nodes representing language constructs like variables, functions, and expressions.

import ts from "typescript";
const sf = ts.createSourceFile(
  "example.ts",
  "const x = 1;",
  ts.ScriptTarget.Latest
);

Node Kinds

Every AST node has a kind property (a ts.SyntaxKind enum value) indicating what it represents.

import ts from "typescript";
// Common kinds:
// ts.SyntaxKind.VariableDeclaration
// ts.SyntaxKind.FunctionDeclaration
// ts.SyntaxKind.Identifier

Visiting with forEachChild

ts.forEachChild(node, visitor) calls your visitor for each direct child of a node. Use recursion to traverse the full tree.

function visit(node: ts.Node) {
  if (ts.isFunctionDeclaration(node)) {
    console.log("Function:", node.name?.text);
  }
  ts.forEachChild(node, visit);
}
visit(sourceFile);

Type Guard Functions

TypeScript provides type-guard functions like ts.isVariableDeclaration and ts.isFunctionDeclaration for safe node narrowing.

ts.forEachChild(sf, node => {
  if (ts.isClassDeclaration(node)) {
    console.log("Class:", node.name?.getText());
  }
  if (ts.isInterfaceDeclaration(node)) {
    console.log("Interface:", node.name.getText());
  }
});

Getting Node Text

Use node.getText(sourceFile) to retrieve the exact source text of a node, or node.getFullText() including trivia.

ts.forEachChild(sf, node => {
  if (ts.isIdentifier(node)) {
    console.log("Id:", node.text);
  }
});

Node Positions

Every node has pos and end positions (character offsets) which you can use to locate nodes in the source.

ts.forEachChild(sf, node => {
  console.log(node.kind, "at", node.pos, "-", node.end);
});

Walking with a Recursive Helper

A common utility is a walk function that recursively applies a visitor to every node in the tree.

function walk(node: ts.Node, visitor: (n: ts.Node) => void) {
  visitor(node);
  ts.forEachChild(node, child => walk(child, visitor));
}

Finding All Function Calls

Use a recursive walk to find all call expressions in a source file — useful for detecting API usage.

walk(sf, node => {
  if (ts.isCallExpression(node)) {
    const expr = node.expression.getText(sf);
    console.log("Call:", expr);
  }
});

Accessing Parent Nodes

AST nodes do not have a parent pointer by default. Call ts.setParent(sourceFile) or use program.getSourceFile which sets parents automatically for programs.

// For manually created source files:
// (ts as any).setParents(sf);

Using the TypeChecker with Nodes

Combine AST traversal with the type checker to resolve the TypeScript type of any expression node.

const checker = program.getTypeChecker();
walk(sf, node => {
  if (ts.isExpression(node)) {
    const type = checker.getTypeAtLocation(node);
    console.log(checker.typeToString(type));
  }
});

Recap: AST Traversal

Traverse the TypeScript AST with forEachChild and type-guard functions. Combine with the type checker to build powerful static analysis and code generation tools.

Quick Check

Which function recursively visits child nodes in the TypeScript AST?

What You Learned

AST traversal uses ts.forEachChild plus type-guard functions to walk and inspect every node in a TypeScript file. Combined with the type checker, it enables linters, code analyzers, and refactoring tools.

Frequently asked questions

Is the “Traversing the AST with Visitors” lesson free?

Yes — the full text of “Traversing the AST with Visitors” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Traversing the AST with Visitors”?

Walk syntax tree nodes to analyze code structure. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start TypeScript Academy?

No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Traversing the AST with Visitors” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this TypeScript Academy lesson?

Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Creating a TypeScript Program with the API
  2. Traversing the AST with Visitors
  3. Custom Transformers and Code Generation
  4. Building a Simple Linting Tool
← Back to TypeScript Academy