TypeScript Compiler API

ts.TransformerFactory<T>

A factory initializes a transformer using a context, then returns a callback that transforms roots. The factory and returned callback are different stages; keep per-root state inside the returned callback when appropriate. The generic type specifies the root node shape; it is a type alias, not a runtime constructor. 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
type TransformerFactory<T extends ts.Node> = (context: ts.TransformationContext) => ts.Transformer<T>; type Transformer<T extends ts.Node> = (node: T) => T

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 });let factories = 0, roots = 0;const identity = context => { factories++; assert(context.factory); return root => { roots++; return root; }; };const other = ts.createSourceFile("other.ts", "let x = 1;", ts.ScriptTarget.ES2022, true);const result = ts.transform([source, other], [identity]);try { assert.equal(result.transformed.length, 2); assert.deepEqual([factories, roots], [1, 2]); console.log(factories, roots); } finally { result.dispose(); }
// Run: node example.cjs// Expected stdout: 1 2
TypeScript Reference