TypeScript Compiler API

ts.createPrinter()

Creates a printer for AST nodes. Options control aspects of formatting such as newline kind and comment removal. Printing is not emission: it can retain TypeScript annotations and does not perform type checking or downlevel transformations. It is not a general-purpose formatter that guarantees preservation of source whitespace. 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
ts.createPrinter(printerOptions?: ts.PrinterOptions, handlers?: ts.PrintHandlers): ts.Printer

Parameters & Attributes

NameTypeDescription
printerOptionsts.PrinterOptionsOptional output preferences.
handlersts.PrintHandlersOptional printer hooks.

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", "// keep?\nconst x: number = 1;", ts.ScriptTarget.ES2022, true);const printer = ts.createPrinter({ removeComments: true, newLine: ts.NewLineKind.LineFeed });const text = printer.printFile(source);assert(!text.includes("keep?"));assert(text.includes(": number"));console.log(text.trim());
// Run: node example.cjs// Expected stdout: const x: number = 1;
TypeScript Reference