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.SourceFileParameters & Attributes
| Name | Type | Description |
|---|---|---|
| fileName | string | Logical source filename. |
| sourceText | string | Source text to parse. |
| languageVersionOrOptions | ts.ScriptTarget | ts.CreateSourceFileOptions | Parsing target or source-file options. |
| setParentNodes | boolean | Populate parent links. |
| scriptKind | ts.ScriptKind | Explicit 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