TypeScript Compiler API
CustomTransformers.after
Runs after built-in JavaScript transformations. The tree may no longer contain TypeScript annotations and may contain lowered constructs or synthetic nodes. A new TypeScript-only construct inserted at this stage is not guaranteed to receive earlier transformations. Test the final JavaScript in the target runtime. 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
customTransformers.after?: (ts.TransformerFactory<ts.SourceFile> | ts.CustomTransformerFactory)[]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 options = { strict: true, types: [], target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, noEmitOnError: true, declaration: true };const program = ts.createProgram(["input.ts"], options);assert.deepEqual(ts.getPreEmitDiagnostics(program).map(d => d.code), []);const fs = require("node:fs");const outputs = new Map();const write = (name, text) => outputs.set(name, text);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);};let annotations = 0;const after = context => root => { function inspect(n) { if (ts.isVariableDeclaration(n) && n.type) annotations++; ts.forEachChild(n, inspect); } inspect(root); return replaceSeven(context)(root);};const result = program.emit(undefined, write, undefined, false, { after: [after] });assert(!result.emitSkipped);assert.equal(annotations, 0);const js = outputs.get("input.js");assert(js.includes("exports.count = 8"));fs.writeFileSync("generated.cjs", js);console.log(annotations, require("./generated.cjs").count);
// File: input.ts (omit this label)export const count: number = 7;
// Run: node example.cjs// Expected stdout: 0 8