TypeScript Compiler API
Printer.printFile()
Prints an entire source file, including its statement list. A source file may be parsed or updated by a factory. TypeScript-specific syntax can remain; use program.emit or an isolated transpilation API when JavaScript output is required. Output formatting can differ from the 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
printer.printFile(sourceFile: ts.SourceFile): stringParameters & Attributes
| Name | Type | Description |
|---|---|---|
| sourceFile | ts.SourceFile | File tree to print. |
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 text = printer.printFile(source);assert.equal(text, "const count: number = 7;\n");console.log(text.trim());
// Run: node example.cjs// Expected stdout: const count: number = 7;