TypeScript
Node creation
Learn to produce AST nodes with ts.factory.
What is ts.factory?
ts.factory is the object in the TypeScript compiler that produces new AST nodes. It has methods like createIdentifier, createNumericLiteral and createStringLiteral for every kind of node. It replaces the older ts.createNode-style API.
const id = ts.factory.createIdentifier("merhaba");
const num = ts.factory.createNumericLiteral("42");
const str = ts.factory.createStringLiteral("selam");
The produced nodes are used inside transformers or in hand-built ASTs.
Combining nodes
You combine nodes to build complex expressions. For console.log(42) you build: console.log with createPropertyAccessExpression, the call with createCallExpression, and the statement with createExpressionStatement.
const call = ts.factory.createCallExpression(
ts.factory.createPropertyAccessExpression(
ts.factory.createIdentifier("console"),
ts.factory.createIdentifier("log")
),
undefined,
[ts.factory.createNumericLiteral("42")]
);
Exercise Build a console.log(42) node
Build console.log(42) with ts.factory: produce console.log with PropertyAccessExpression, the call with CallExpression, and the statement with ExpressionStatement. Print the result with ts.createPrinter and printNode.
Show example solution
import ts from "typescript";
const dummy = ts.createSourceFile("dummy.ts", "", ts.ScriptTarget.Latest, true);
const call = ts.factory.createCallExpression(
ts.factory.createPropertyAccessExpression(
ts.factory.createIdentifier("console"),
ts.factory.createIdentifier("log")
),
undefined,
[ts.factory.createNumericLiteral("42")]
);
const stmt = ts.factory.createExpressionStatement(call);
const printer = ts.createPrinter();
console.log(printer.printNode(ts.EmitHint.Unspecified, stmt, dummy));
Test yourself
-
What does ts.factory.createIdentifier("x") return?
- An Identifier node
- A Symbol object
- A string value
- A Type object
Show answer
An Identifier node — createIdentifier returns a new Identifier AST node, not a string, Type or Symbol.
-
Create a numeric node
const num = ts.factory.____("42");
Show answer
const num = ts.factory.createNumericLiteral("42");
-
factory parts
- ts.factory.createIdentifier
- Produces an Identifier node
- ts.factory.createNumericLiteral
- Produces a NumericLiteral node
- ts.factory.createCallExpression
- Produces a call expression
- ts.factory.createExpressionStatement
- Produces a statement
Next lesson: Custom transformer