TypeScript Compiler API

ts.createSourceFile()

Parses source text into a SourceFile containing an abstract syntax tree (AST). Parsing does not load imported files or establish semantic correctness. The parent-link argument is useful for traversing back to enclosing syntax; scriptKind can override extension-based interpretation. 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.createSourceFile(fileName, sourceText, languageVersionOrOptions, setParentNodes?, scriptKind?): ts.SourceFile

Parameters & Attributes

NameTypeDescription
fileNamestringLogical source filename.
sourceTextstringSource text to parse.
languageVersionOrOptionsts.ScriptTarget | ts.CreateSourceFileOptionsParsing target or source-file options.
setParentNodesbooleanPopulate parent links.
scriptKindts.ScriptKindExplicit source kind, e.g. TSX.

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 = 7;", ts.ScriptTarget.ES2022, true);const declaration = source.statements[0].declarationList.declarations[0];assert(ts.isVariableDeclaration(declaration));assert.equal(declaration.name.getText(source), "count");console.log(declaration.name.getText(source), declaration.initializer.getText(source));
// Run: node example.cjs// Expected stdout: count 7
// Separate variation in a fresh directory.// File: example.cjs (omit this label)const ts = require("typescript");const assert = require("node:assert/strict");const source = ts.createSourceFile("bad.ts", 'const n: number = "bad";', ts.ScriptTarget.ES2022, true);assert(ts.isSourceFile(source));assert.equal(source.statements.length, 1);console.log("parsed");
// Run: node example.cjs// Expected stdout: parsed
TypeScript Reference