TypeScript Compiler API

ts.createProgram()

Creates a program from root source files and compiler options, resolving reachable dependencies through a compiler host. It does not automatically read tsconfig.json when called with a root list and options. Use diagnostic APIs and emit explicitly. A previous program can support reuse when appropriate; this example uses a fresh 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
ts.createProgram(rootNames, options, host?, oldProgram?, configFileParsingDiagnostics?): ts.Program; ts.createProgram(createProgramOptions): ts.Program

Parameters & Attributes

NameTypeDescription
rootNamesreadonly string[]Entry file paths.
optionsts.CompilerOptionsCompiler API options.
hostts.CompilerHostOptional filesystem/environment adapter.
oldProgramts.ProgramPrevious program for reuse.
configFileParsingDiagnosticsreadonly ts.Diagnostic[]Diagnostics from prior configuration parsing.

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 options = { strict: true, types: [], target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS };const program = ts.createProgram(["input.ts"], options);const roots = program.getRootFileNames();assert.deepEqual(roots, ["input.ts"]);assert(program.getSourceFiles().some(f => f.fileName.endsWith("dep.ts")));assert.equal(ts.getPreEmitDiagnostics(program).length, 0);console.log(roots.length, "dependency loaded");
// File: input.ts (omit this label)import { n } from "./dep"; export const result = n * 2;
// File: dep.ts (omit this label)export const n = 7;
// Run: node example.cjs// Expected stdout: 1 dependency loaded
TypeScript Reference