TypeScript Compiler API

ts.TransformationContext

Provides factory methods, compiler options and transformation services while a transformer runs. Hook initialization and lexical-environment management require care; use the supplied context with visitEachChild to support the transformation machinery. It is not a TypeChecker and does not provide semantic analysis by itself. 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
interface ts.TransformationContext; context.factory: ts.NodeFactory; context.getCompilerOptions(): ts.CompilerOptions

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 options = { target: ts.ScriptTarget.ES2017 };const transformer = context => root => {  assert.equal(context.getCompilerOptions().target, ts.ScriptTarget.ES2017);  const f = context.factory;  const statement = f.createExpressionStatement(f.createStringLiteral("context"));  return f.updateSourceFile(root, [statement]);};const result = ts.transform(source, [transformer], options);try { console.log(printer.printFile(result.transformed[0]).trim()); } finally { result.dispose(); }
// Run: node example.cjs// Expected stdout: "context";
TypeScript Reference