TypeScript Compiler API

Printer.printNode()

Prints a single node and its subtree without built-in emit transformations. Supply a source file as context, especially when printing original parsed nodes. EmitHint.Unspecified is appropriate for many nodes; Expression and IdentifierName indicate particular syntax roles. The resulting string does not prove that the node is semantically valid. 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
printer.printNode(hint: ts.EmitHint, node: ts.Node, sourceFile: ts.SourceFile): string

Parameters & Attributes

NameTypeDescription
hintts.EmitHintNode usage hint.
nodets.NodeNode to print.
sourceFilets.SourceFileSource context for text and names.

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 declaration = source.statements[0].declarationList.declarations[0];const text = printer.printNode(ts.EmitHint.Unspecified, declaration, source);assert(!text.startsWith("const"));console.log(text);
// Run: node example.cjs// Expected stdout: count: number = 7
TypeScript Reference