TypeScript Compiler API
ts.formatDiagnostics()
Formats diagnostic objects into plain human-readable output with locations when present. The host supplies path canonicalization, current directory and newline policy. For machine processing retain structured diagnostic fields; use formatDiagnosticsWithColorAndContext for terminal-oriented context instead of parsing formatted text. 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.formatDiagnostics(diagnostics, host): stringParameters & Attributes
| Name | Type | Description |
|---|---|---|
| diagnostics | readonly ts.Diagnostic[] | Diagnostic objects to format. |
| host | ts.FormatDiagnosticsHost | Filename, directory and newline helpers. |
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 host = { getCanonicalFileName: name => name, getCurrentDirectory: () => process.cwd(), getNewLine: () => "\n" };const text = ts.formatDiagnostics(ts.getPreEmitDiagnostics(program), host);assert(text.includes("input.ts(1,14): error TS2322:"));assert(text.includes("not assignable"));console.log("location and code present");
// File: input.ts (omit this label)export const n: number = "bad";
// Run: node example.cjs// Expected stdout: location and code present