TypeScript Compiler API
ts.createCompilerHost()
Constructs a default host that adapts compiler operations to the local system, including reading files, resolving paths and writing generated files. Override specific methods for controlled tooling; retain default methods for library and dependency lookup. A custom readFile alone is not necessarily sufficient for a complete virtual filesystem. 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.createCompilerHost(options, setParentNodes?): ts.CompilerHostParameters & Attributes
| Name | Type | Description |
|---|---|---|
| options | ts.CompilerOptions | Compiler settings used by the host. |
| setParentNodes | boolean | Populate parent links when parsing files. |
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 host = ts.createCompilerHost(options);const outputs = new Map();host.writeFile = (name, text) => { outputs.set(name, text); };const program = ts.createProgram(["input.ts"], options, host);assert.equal(ts.getPreEmitDiagnostics(program).length, 0);assert.equal(program.emit().emitSkipped, false);assert.equal(outputs.size, 1);assert(!require("node:fs").existsSync("input.js"));console.log("captured", outputs.size);
// File: input.ts (omit this label)export const n: number = 7;
// Run: node example.cjs// Expected stdout: captured 1