TypeScript Compiler API
Program.emit()
Emits JavaScript and/or declaration files as configured. With a write callback, output can be captured rather than written to disk. The result reports emitSkipped and emission diagnostics; these do not replace pre-emit checks. noEmit and noEmitOnError influence output. Declaration-only emission requires suitable declaration settings. 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
program.emit(targetSourceFile?, writeFile?, cancellationToken?, emitOnlyDtsFiles?, customTransformers?): ts.EmitResultParameters & Attributes
| Name | Type | Description |
|---|---|---|
| targetSourceFile | ts.SourceFile | Optional specific file to emit. |
| writeFile | ts.WriteFileCallback | Output callback, otherwise host writes files. |
| cancellationToken | ts.CancellationToken | Cooperative cancellation. |
| emitOnlyDtsFiles | boolean | Limit emission to declarations when configured. |
| customTransformers | ts.CustomTransformers | Optional transformation hooks. |
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, declaration: true, noEmitOnError: true });assert.equal(ts.getPreEmitDiagnostics(program).length, 0);const outputs = new Map();const result = program.emit(undefined, (name, text) => { outputs.set(name, text); });assert.equal(result.emitSkipped, false);assert.equal(result.diagnostics.length, 0);assert(outputs.get("input.d.ts").includes("n: number"));assert(outputs.get("input.js").includes("exports.n = 7"));console.log([...outputs.keys()].sort().join(","));
// File: input.ts (omit this label)export const n: number = 7;
// Run: node example.cjs// Expected stdout: input.d.ts,input.js
// Separate variation in a fresh directory.// 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, noEmitOnError: true });assert.deepEqual(ts.getPreEmitDiagnostics(program).map(d => d.code), [2322]);let writes = 0;const result = program.emit(undefined, () => { writes++; });assert.equal(result.emitSkipped, true);assert.equal(writes, 0);console.log(result.emitSkipped, writes);
// File: input.ts (omit this label)export const n: number = "bad";
// Run: node example.cjs// Expected stdout: true 0