Course contentsShow
← TypeScript
Lesson 1101 of 1,79626. Modules in TypeScriptFree lesson

CommonJS interop and type imports

Handle type imports when working with CommonJS modules using esModuleInterop.

CommonJS Interop and Type Imports

What you'll learn: How to properly import types when working with CommonJS modules, especially when esModuleInterop is enabled.

The Problem TypeScript Solves

When you import a CommonJS module (the older Node.js module system using require and module.exports), TypeScript needs to understand how to map those imports to types. Without proper configuration, you might see confusing errors when trying to import both values and types from the same module.

Understanding the Interop Gap

CommonJS and ES Modules handle exports differently. A CommonJS module might export a single default value like this:

// A CommonJS library
module.exports = function logger(msg) { ... }

But TypeScript's type system expects ES Module syntax. This creates a mismatch that esModuleInterop fixes by making imports "just work" the way you'd expect.

Type Imports with CommonJS Modules

When importing types from CommonJS modules, you can use import type safely:

import type { Config } from 'some-commonjs-library';
import { processData } from 'some-commonjs-library';

The esModuleInterop flag ensures that both the type-only import and the value import work correctly, even though the underlying module uses CommonJS. TypeScript handles the translation behind the scenes.

Why This Matters for Type-Only Imports

Type-only imports get erased at compile time, but the compiler still needs to understand the module's shape. With esModuleInterop enabled, you avoid awkward patterns like import * as Module when you just want types, keeping your imports clean and consistent whether the source is ESM or CommonJS.

Key Takeaway: esModuleInterop allows you to use modern import type syntax seamlessly with CommonJS modules, letting TypeScript handle the module system differences while keeping type-only imports clean and bundle-friendly.