TypeScript Compiler API
ts.Node
The shared interface for AST nodes. A node exposes its kind and source positions; specialized guards narrow it to more specific structures. getText returns source text; getStart normally excludes leading trivia while getFullStart includes it. Positions are zero-based UTF-16 offsets, not line numbers. Parent links must have been populated; synthesized nodes may lack original source text. 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
interface ts.Node; node.getText(sourceFile?); node.getStart(sourceFile?, includeJsDocComment?); node.getEnd()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", "// heading\nconst count = 7;", ts.ScriptTarget.ES2022, true);const node = source.statements[0];assert.equal(node.parent, source);assert.equal(node.getFullStart(), 0);assert.equal(node.getStart(source), 11);assert.equal(node.getEnd(), 27);console.log(node.getFullStart(), node.getStart(source), node.getEnd());console.log(node.getText(source));
// Run: node example.cjs// Expected stdout: 0 11 27// const count = 7;