Incremental and watch APIs
Concept and boundary
Incremental builders maintain state to avoid unnecessary repeated work. Use an incremental host that supplies source versions; build information is version-specific cache data. Watch programs react to host notifications and must release watch registrations. Controlled callbacks test compiler behavior, not native filesystem reliability.
Local tooling setup
For each workshop use a fresh folder. Install the pinned compiler with npm install --save-dev typescript@5.8.3, then create the listed files and run node example.cjs with Node.js 22.16.0. Assertions fail if the expected behavior changes. These are local JavaScript tooling scripts, not browser CodeRunner tasks; they do not independently type-check the tooling source.
Workshop 1: create-incremental-program
Revisit reference fixture ts-api-create-incremental-program (historical V26, rerun in V74).
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 = 7;");const builder = ts.createIncrementalProgram({ rootNames: [root], options });assert.deepEqual(ts.getPreEmitDiagnostics(builder.getProgram()), []);assert.equal(builder.emit().emitSkipped, false);assert(fs.existsSync("cache/state.tsbuildinfo"));assert(fs.existsSync("dist/main.d.ts"));console.log("build info and declarations created");Expected stdout (exit 0):
build info and declarations createdWorkshop 2: create-watch-program
Revisit reference fixture ts-api-create-watch-program (historical V26, rerun in V74).
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);}// Controlled notifications and timers; actual file reads/writes use ts.sys.function controlledSystem() { const watchers = new Map(), directories = new Set(), timers = new Map(); let serial = 0; const system = { ...ts.sys, watchFile(name, cb) { const key = path.resolve(name); const list = watchers.get(key) ?? new Set(); watchers.set(key, list); list.add(cb); return { close() { list.delete(cb); } }; }, watchDirectory(name, cb) { const entry = { name, cb }; directories.add(entry); return { close() { directories.delete(entry); } }; }, setTimeout(cb, ms, ...args) { const id = ++serial; timers.set(id, () => cb(...args)); return id; }, clearTimeout(id) { timers.delete(id); } }; function change(name, text) { const key = path.resolve(name); const callbacks = [...(watchers.get(key) ?? [])]; assert(callbacks.length > 0, "file must be watched"); put(key, text); // Force a distinct modification time even on coarse filesystems. const later = new Date(Date.now() + 2000); fs.utimesSync(key, later, later); for (const cb of callbacks) cb(key, ts.FileWatcherEventKind.Changed); } function drain() { for (let count = 0; timers.size; count++) { assert(count < 50, "timer loop did not settle"); const [id, cb] = timers.entries().next().value; timers.delete(id); cb(); } } return { system, change, drain, active: () => [...watchers.values()].reduce((n, s) => n+s.size, 0)+directories.size, clear: () => { watchers.clear(); directories.clear(); timers.clear(); } };}put("main.ts", "export const n: number = 7;");const root = path.resolve("main.ts"), c = controlledSystem();const host = ts.createWatchCompilerHost([root], { strict: true, noEmit: true, types: [] }, c.system, ts.createSemanticDiagnosticsBuilderProgram, () => {}, () => {});const watcher = ts.createWatchProgram(host);try { assert.deepEqual(watcher.getProgram().getSemanticDiagnostics(), []); c.change(root, 'export const n: number = "bad";'); c.drain(); assert.deepEqual(watcher.getProgram().getSemanticDiagnostics().map(d=>d.code), [2322]); console.log("clean -> 2322");} finally { watcher.close(); c.clear(); }Expected stdout (exit 0):
clean -> 2322Practice and recap
Introduce a type error after a clean build and check the new diagnostics.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Incremental and watch APIs — knowledge check
Check the concept and interpret the locally verified compiler tooling probes.
Which statement correctly describes Incremental and watch APIs?
What does workshop 1 (create-incremental-program) print when run unchanged with the specified compiler?
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 = 7;");const builder = ts.createIncrementalProgram({ rootNames: [root], options });assert.deepEqual(ts.getPreEmitDiagnostics(builder.getProgram()), []);assert.equal(builder.emit().emitSkipped, false);assert(fs.existsSync("cache/state.tsbuildinfo"));assert(fs.existsSync("dist/main.d.ts"));console.log("build info and declarations created");What does workshop 2 (create-watch-program) print when run unchanged with the specified compiler?
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);}// Controlled notifications and timers; actual file reads/writes use ts.sys.function controlledSystem() { const watchers = new Map(), directories = new Set(), timers = new Map(); let serial = 0; const system = { ...ts.sys, watchFile(name, cb) { const key = path.resolve(name); const list = watchers.get(key) ?? new Set(); watchers.set(key, list); list.add(cb); return { close() { list.delete(cb); } }; }, watchDirectory(name, cb) { const entry = { name, cb }; directories.add(entry); return { close() { directories.delete(entry); } }; }, setTimeout(cb, ms, ...args) { const id = ++serial; timers.set(id, () => cb(...args)); return id; }, clearTimeout(id) { timers.delete(id); } }; function change(name, text) { const key = path.resolve(name); const callbacks = [...(watchers.get(key) ?? [])]; assert(callbacks.length > 0, "file must be watched"); put(key, text); // Force a distinct modification time even on coarse filesystems. const later = new Date(Date.now() + 2000); fs.utimesSync(key, later, later); for (const cb of callbacks) cb(key, ts.FileWatcherEventKind.Changed); } function drain() { for (let count = 0; timers.size; count++) { assert(count < 50, "timer loop did not settle"); const [id, cb] = timers.entries().next().value; timers.delete(id); cb(); } } return { system, change, drain, active: () => [...watchers.values()].reduce((n, s) => n+s.size, 0)+directories.size, clear: () => { watchers.clear(); directories.clear(); timers.clear(); } };}put("main.ts", "export const n: number = 7;");const root = path.resolve("main.ts"), c = controlledSystem();const host = ts.createWatchCompilerHost([root], { strict: true, noEmit: true, types: [] }, c.system, ts.createSemanticDiagnosticsBuilderProgram, () => {}, () => {});const watcher = ts.createWatchProgram(host);try { assert.deepEqual(watcher.getProgram().getSemanticDiagnostics(), []); c.change(root, 'export const n: number = "bad";'); c.drain(); assert.deepEqual(watcher.getProgram().getSemanticDiagnostics().map(d=>d.code), [2322]); console.log("clean -> 2322");} finally { watcher.close(); c.clear(); }