TypeScript
What is a transformer?
Learn transformer functions.
Transformer function
A transformer is a function in the TypeScript compiler that transforms AST nodes. It has type ts.TransformerFactory<T>: it takes a TransformationContext and returns a visitor function. The visitor receives each node and returns the same node or a new one.
import ts from "typescript";
const transformer: ts.TransformerFactory<ts.SourceFile> =
(context) => (node) => {
return ts.visitEachChild(node, visit, context);
};
Transformers are applied to source files with ts.transform.
ts.transform and visitEachChild
ts.transform(source, transformers) transforms a source node with the given transformers and returns a TransformResult. result.transformed[0] is the transformed root node. To transform child nodes you use ts.visitEachChild(node, visitor, context).
const result = ts.transform(sf, [transformer]);
const out = result.transformed[0];
result.dispose();
When done, call result.dispose() to clean up memory.
Exercise Identity transformer
Create a SourceFile from const x = 1;. Define a ts.TransformerFactory whose visitor returns the node unchanged (identity). Apply it with ts.transform and print the transformed source with ts.createPrinter.
Show example solution
import ts from "typescript";
const sourceText = "const x = 1;";
const sf = ts.createSourceFile("app.ts", sourceText, ts.ScriptTarget.Latest, true);
const transformer: ts.TransformerFactory<ts.SourceFile> = (context) => (node) => {
return node;
};
const result = ts.transform(sf, [transformer]);
const printer = ts.createPrinter();
process.stdout.write(printer.printFile(result.transformed[0] as ts.SourceFile));
result.dispose();
Test yourself
-
What signature does a TransformerFactory have?
- (node) => node
- (source) => string
- (program) => TypeChecker
- (context) => (node) => node
Show answer
(context) => (node) => node — A TransformerFactory takes a TransformationContext and returns a (node) => node visitor function. It does not take a node or source directly.
-
Visit child nodes
const transformer: ts.TransformerFactory<ts.SourceFile> = (context) => (node) => {
return ts.____(node, visit, context);
};
Show answer
const transformer: ts.TransformerFactory<ts.SourceFile> = (context) => (node) => {
return ts.visitEachChild(node, visit, context);
};
-
Transformer parts
- ts.TransformerFactory
- Transformer function type
- ts.transform
- Applies the transformation
- visitEachChild
- Transforms child nodes
- TransformResult
- Holds the transformed root
Next lesson: Node creation