TypeScript Compiler API
ts.factory
The public default node factory constructs and updates AST nodes. Factory-created nodes are synthetic; they need not carry original source ranges or semantic symbols. Prefer context.factory within a transformer. Factory calls do not type-check the resulting tree. 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
ts.factory: ts.NodeFactoryWorking 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 expression = ts.factory.createBinaryExpression(ts.factory.createNumericLiteral(2), ts.SyntaxKind.PlusToken, ts.factory.createNumericLiteral(3));assert(ts.isBinaryExpression(expression));console.log(printer.printNode(ts.EmitHint.Expression, expression, source));
// Run: node example.cjs// Expected stdout: 2 + 3