TypeScript Compiler API

TypeScript transpileModule

Use the TypeScript transpileModule API to convert source code without a full program, configure compiler options, and understand its type-checking limits.

Formal Syntax & Structure

typescript syntaxtypescript
ts.transpileModule(input, transpileOptions): ts.TranspileOutput

Parameters & Attributes

NameTypeDescription
inputstringSource text.
transpileOptionsts.TranspileOptionsCompiler settings, filename, diagnostic reporting and optional transforms.

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 source = 'const n: number = "bad"; console.log(typeof n);';const result = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }, fileName: "input.ts", reportDiagnostics: true });assert.equal(result.diagnostics.length, 0);assert(!result.outputText.includes(": number"));const fs = require("node:fs");fs.writeFileSync("generated.cjs", result.outputText);const output = require("node:child_process").execFileSync(process.execPath, ["generated.cjs"], { encoding: "utf8" }).trim();assert.equal(output, "string");console.log(result.diagnostics.length, output);
// Run: node example.cjs// Expected stdout: 0 string
// Separate variation in a fresh directory.// File: example.cjs (omit this label)const ts = require("typescript");const assert = require("node:assert/strict");const result = ts.transpileModule("const n = ;", { fileName: "input.ts", reportDiagnostics: true, compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } });assert.deepEqual(result.diagnostics.map(d => d.code), [1109]);console.log(result.diagnostics[0].code);
// Run: node example.cjs// Expected stdout: 1109
TypeScript Reference