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.SourceFile

Parameters & Attributes

NameTypeDescription
nodets.SourceFileExisting source file.
statementsreadonly ts.Statement[]Replacement statements.
isDeclarationFilebooleanDeclaration-file flag.
referencedFilesreadonly ts.FileReference[]Path references.
typeReferencesreadonly ts.FileReference[]Type reference directives.
hasNoDefaultLibbooleanDefault-library directive flag.
libReferencesreadonly 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);
TypeScript Reference