TypeScript Advanced Declaration Authoring
CommonJS object export declarations
For a package assigning an object to module.exports, export = can describe the complete exported object. This is different from promising a default ESM export. Use import = require in the CommonJS consumer to avoid depending on synthetic default import interop. Baseline: TypeScript 5.8.3, strict NodeNext consumer unless otherwise noted. Create the labeled files separately; do not paste this project into a single-file editor.
Formal Syntax & Structure
typescript syntaxtypescript
declare const api: { read(): number }; export = api;Working Example
Example Snippettypescript
// File: tsconfig.json (omit this label){ "compilerOptions": { "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext", "strict": true, "types": [], "lib": [ "ES2022", "DOM" ], "noEmitOnError": true }, "files": [ "main.cts" ]}
// File: node_modules/demo/package.json (omit this label){ "name": "demo", "version": "1.0.0", "main": "./index.cjs", "types": "./index.d.cts"}
// File: node_modules/demo/index.d.cts (omit this label)declare const api: { read(): number; reset(): void };export = api;
// File: node_modules/demo/index.cjs (omit this label)let value = 5; module.exports = { read: () => value, reset: () => { value = 0; } };
// File: main.cts (omit this label)import api = require("demo");console.log(api.read()); api.reset(); console.log(api.read());
// Run: tsc -p . --pretty false// Expected: no diagnostics.// Run: node main.cjs// Expected stdout: 5\n0