Menu

Modules, Imports, and Type-Only Imports

Lesson 1: Modules, Imports, and Type-Only Imports

How does TypeScript handle modules?

Any file with a top-level import or export is a module with its own scope. TypeScript follows the JavaScript ES module syntax and adds type-only imports.

Syntax Imports Kept in the output?
import { formatPrice } from './price.ts' A value Yes
import type { Product } from './types.ts' Only a type No (removed)
import { type Product, formatPrice } from './x.ts' Mixed Only the value
export type { Product } Re-export a type No

Example

// src/types.ts
export interface Product {
  id: string;
  name: string;
  price: number;
}
export type OrderStatus = 'pending' | 'shipped' | 'delivered';
// src/price.ts
import type { Product } from './types.ts';

export function formatPrice(product: Product): string {
  return `₹${(product.price / 100).toFixed(2)}`;
}

export const GST_RATE = 5;
// src/index.ts
import { formatPrice, GST_RATE } from './price.ts';
import type { Product, OrderStatus } from './types.ts';

const milk: Product = { id: 'p1', name: 'Milk 1L', price: 6400 };
console.log(formatPrice(milk), GST_RATE);

How it works

  • import type tells every tool that the import can be deleted, which matters for tools that compile one file at a time and for Node.js type stripping.
  • The verbatimModuleSyntax option enforces this: any import used only as a type must be written as import type, and everything else is kept exactly as written.
  • File extensions: with module: nodenext (Node.js) or Node type stripping, relative imports need extensions. Write ./price.ts and enable rewriteRelativeImportExtensions if tsc should change them to .js in the output, or write ./price.js with classic tsc builds. Bundlers (Vite, Next.js) usually allow imports without extensions.
  • TypeScript 6.0 added support for Node.js #/ subpath imports, such as import { db } from '#/lib/db.ts', under nodenext and bundler resolution.

Common mistakes

Mistake Effect Fix
Importing types with a normal import under verbatimModuleSyntax Error, or runtime import of a missing value Use import type
Missing file extensions in Node.js ESM projects "Cannot find module" at runtime Add .ts or .js extensions as your setup requires
Circular imports between modules undefined values at runtime Move shared types to a separate types.ts file

Key takeaways

  • Use ES module syntax; mark type-only imports with import type.
  • Match import extensions to how your code runs.

Try it: Split the QuickCart cart code into types.ts, cart.ts, and index.ts, using import type for every type-only import.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details