TypeScript Compiler API

Incremental compiler state management

Persistent build information is compiler-private state, not an application interchange format. A compatible incremental builder can read it; missing or unusable state should permit a fresh build. Keep cache paths separate for distinct projects and compiler versions, and never treat cache presence as proof of correctness. The fixture verifies clean initial cache absence and restart after source change, not performance savings. Baseline: TypeScript 5.8.3, Node.js. Run as a local tooling script in a disposable directory; examples create files. Not a ByteMind CodeRunner example.

Formal Syntax & Structure

typescript syntaxtypescript
ts.readBuilderProgram(compilerOptions: ts.CompilerOptions, host: ts.ReadBuildProgramHost): ts.EmitAndSemanticDiagnosticsBuilderProgram | undefined

Parameters & Attributes

NameTypeDescription
compilerOptionsts.CompilerOptionsSettings identifying the cache.
hostts.ReadBuildProgramHostFile reader, current directory and case-sensitivity function.

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 fs = require("node:fs");const path = require("node:path");function put(name, text) {  fs.mkdirSync(path.dirname(name), { recursive: true });  fs.writeFileSync(name, text);}const options = { strict: true, target: ts.ScriptTarget.ES2022,  module: ts.ModuleKind.CommonJS, types: [], incremental: true,  declaration: true, outDir: "dist", tsBuildInfoFile: "cache/state.tsbuildinfo" };const root = path.resolve("main.ts");put(root, "export const n: number = 1;");const host = { readFile: ts.sys.readFile, getCurrentDirectory: ts.sys.getCurrentDirectory,  useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames };assert.equal(ts.readBuilderProgram(options, host), undefined);let b = ts.createIncrementalProgram({ rootNames: [root], options });assert.deepEqual(b.getSemanticDiagnostics(), []); b.emit();assert(ts.readBuilderProgram(options, host));put(root, 'export const n: number = "bad";');b = ts.createIncrementalProgram({ rootNames: [root], options });assert.deepEqual(b.getSemanticDiagnostics().map(d=>d.code), [2322]);console.log("missing -> readable cache -> 2322");
// Run: node example.cjs// Expected stdout: missing -> readable cache -> 2322
TypeScript Reference