TypeScript Compiler API

ts.getPreEmitDiagnostics()

Collects compiler diagnostics before emission, including applicable option, syntax, global, semantic and declaration diagnostics. The optional file narrows applicable file checks, not all global or option diagnostics. It does not perform emission or guarantee an error-free future runtime; inspect emit diagnostics separately. 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.getPreEmitDiagnostics(program, sourceFile?, cancellationToken?): readonly ts.Diagnostic[]

Parameters & Attributes

NameTypeDescription
programts.ProgramProgram to check.
sourceFilets.SourceFileOptional file scope.
cancellationTokents.CancellationTokenOptional cooperative cancellation.

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 codes = ts.getPreEmitDiagnostics(program).map(d => d.code);assert.deepEqual(codes, [2322]);console.log(codes.join(","));
// File: input.ts (omit this label)export const n: number = "bad";
// Run: node example.cjs// Expected stdout: 2322
// 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);assert.equal(ts.getPreEmitDiagnostics(program).length, 0);console.log("0 diagnostics");
// File: input.ts (omit this label)export const n: number = 7;
// Run: node example.cjs// Expected stdout: 0 diagnostics
TypeScript Reference