JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstypescript
PrevNext
typescript
mid
modules

How do TypeScript modules work and what's the difference between import types?

modules
import
export
declaration-files
types
Quick Answer

TypeScript supports ES6 modules with import/export syntax. Use 'import type' for type-only imports (erased at compile time). Declaration files (.d.ts) provide types for JavaScript libraries. Module resolution follows Node.js or bundler strategies.

Detailed Explanation

Module Syntax:

  • ES6 modules: import/export
  • Named exports: export { name }
  • Default exports: export default
  • Namespace imports: import * as

Type-Only Imports:

  • import type { Type }: Types only, erased at runtime
  • import { type Type }: Inline type modifier
  • Prevents including unused runtime code

Declaration Files (.d.ts):

  • Type definitions without implementation
  • For typing JavaScript libraries
  • @types/* packages from DefinitelyTyped

Module Resolution:

  • Classic: Relative and ambient modules
  • Node: Follows Node.js resolution
  • Bundler: For webpack/vite/esbuild

Code Examples

Import and export syntax
// === Exporting ===
// Named exports
export const PI = 3.14159;
export function add(a: number, b: number): number {
  return a + b;
}
export interface User {
  id: number;
  name: string;
}

// Default export
export default class Calculator {
  add(a: number, b: number) { return a + b; }
}

// Re-exports
export { User as UserType } from './types';
export * from './utils';
export * as MathUtils from './math';

// === Importing ===
// Named imports
import { PI, add, User } from './math';

// Default import
import Calculator from './calculator';

// Namespace import
import * as Math from './math';
Math.add(1, 2);

// Combined
import Calculator, { add, PI } from './calculator';

Resources

TypeScript - Modules

docs

TypeScript - Declaration Files

docs

Related Questions

What are generics in TypeScript and how do you use them?

mid
generics
Previous
What are TypeScript's built-in utility types and when do you use them?
Next
What are enums in TypeScript and when should you use them vs union types?