TypeScript Compiler API

ts.transform()

Applies transformer factories to a node or array of nodes in sequence and returns transformed roots. It does not automatically perform the compiler’s built-in TypeScript-to-JavaScript lowering or recheck types. Consume the result before disposing it, preferably in finally. Keep transformations scoped and avoid modifying source nodes in place. 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.transform<T extends ts.Node>(source: T | T[], transformers: ts.TransformerFactory<T>[], compilerOptions?): ts.TransformationResult<T>

Parameters & Attributes

NameTypeDescription
sourceT | T[]Root or roots to transform.
transformersts.TransformerFactory<T>[]Ordered transformer factories.
compilerOptionsts.CompilerOptionsOptional transformation options.

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 replaceSeven = context => root => {  function visit(node) {    if (ts.isNumericLiteral(node) && node.text === "7") return context.factory.createNumericLiteral(8);    return ts.visitEachChild(node, visit, context);  }  return ts.visitNode(root, visit, ts.isSourceFile);};const result = ts.transform(source, [replaceSeven]);try {  assert.equal(source.statements[0].declarationList.declarations[0].initializer.text, "7");  console.log(printer.printFile(result.transformed[0]).trim());} finally { result.dispose(); }
// Run: node example.cjs// Expected stdout: const count: number = 8;
TypeScript Reference