Skip to main content

Overview

The Parser converts a stream of tokens from the Scanner into an Abstract Syntax Tree (AST). The AST is a tree representation of the source code structure that can be analyzed and transformed.

Creating Source Files

ts.createSourceFile()

Creates a SourceFile AST from source text.
fileName
string
required
The name of the file
sourceText
string
required
The source code text
languageVersionOrOptions
ScriptTarget | CreateSourceFileOptions
required
Either a script target or options object
setParentNodes
boolean
Whether to set parent pointers on nodes (defaults to false)
scriptKind
ScriptKind
The kind of script (TS, JS, JSX, etc.)
return
SourceFile
The parsed source file AST

Example

SourceFile Interface

The SourceFile represents the root of the AST and provides access to the parsed code structure.

Key Properties

Example

Working with the AST

Node Types

The AST consists of various node types, all extending the base Node interface:

Traversing the AST

ts.forEachChild()

Visits each child node of a node.
node
Node
required
The node to visit children of
cbNode
(node: Node) => T | undefined
required
Callback for each child node
return
T | undefined
The first truthy value returned by the callback

Recursive Visitor Pattern

Type Guards

TypeScript provides type guard functions to check node types:
Common type guards:

Analyzing Specific Constructs

Analyzing Functions

Analyzing Classes

Analyzing Imports and Exports

Node Position Information

Complete Example: Code Analyzer

See Also