Advertisement
Advanced TypeScript, Modules

How would you correctly type a module that supports BOTH a default export and several named exports, and how do consumers import it under different esModuleInterop settings?

Short answer

Declare both `export default` and named `export`s normally in the module; how consumers import it depends on esModuleInterop and the module target — with esModuleInterop enabled, `import Default, { named } from 'module'` works cleanly, while under strict ES module interop rules…

Save TypeScript mock interview
Advertisement
AModel answer
Declare both `export default` and named `export`s normally in the module; how consumers import it depends on esModuleInterop and the module target — with esModuleInterop enabled, `import Default, { named } from 'module'` works cleanly, while under strict ES module interop rules without it, you may need `import * as mod from 'module'` and access `mod.default` explicitly.
// mathLib.ts
export default function add(a: number, b: number) { return a + b; }
export const PI = 3.14159;

// consumer.ts (with esModuleInterop: true)
import add, { PI } from './mathLib';
Real-world example
Designing a utility library's public API to offer both a convenient default export and additional named utility exports.
Likely follow-ups
  • What subtle bug can occur if a CommonJS-compiled module's default export handling doesn't match what a consumer's bundler expects?
Related topics