TypeScript Compiler API
NodeFactory.updateSourceFile()
Updates the statement list of a source file using a factory operation; unchanged inputs may return the original node. Preserve unmodified statements and metadata rather than mutating a parsed tree. This is distinct from the top-level ts.updateSourceFile text-edit API, which accepts a text change range. A modified tree is not a newly checked Program. 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
factory.updateSourceFile(node, statements, isDeclarationFile?, referencedFiles?, typeReferences?, hasNoDefaultLib?, libReferences?): ts.SourceFileParameters & Attributes
| Name | Type | Description |
|---|---|---|
| node | ts.SourceFile | Existing source file. |
| statements | readonly ts.Statement[] | Replacement statements. |
| isDeclarationFile | boolean | Declaration-file flag. |
| referencedFiles | readonly ts.FileReference[] | Path references. |
| typeReferences | readonly ts.FileReference[] | Type reference directives. |
| hasNoDefaultLib | boolean | Default-library directive flag. |
| libReferences | readonly ts.FileReference[] | Library reference directives. |
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 f = ts.factory;const extra = f.createExpressionStatement(f.createCallExpression(f.createIdentifier("show"), undefined, [f.createIdentifier("count")]));const updated = f.updateSourceFile(source, [...source.statements, extra]);assert.notEqual(updated, source);assert.equal(source.statements.length, 1);assert.equal(updated.statements[0], source.statements[0]);console.log(printer.printFile(updated).trim());
// Run: node example.cjs// Expected stdout: const count: number = 7;// show(count);