TypeScript · Types that pay for themselves

How do modules work in TypeScript?

Mediummodulesimportsmodule-resolutionUpdated Oct 2026
Quiz this track

Short answer

TypeScript follows JavaScript module semantics. A file with a top-level import or export is a module with its own scope; a file without either is a script sharing the global scope.

The distinction between a module and a script is determined by syntax, not by a file extension. Adding an import or export makes a file a module. Everything in a module is scoped to that file unless it is exported, which avoids accidental globals.

ts
export type User = { id: number };

export function findUser(id: number): User | undefined {
  return id === 1 ? { id } : undefined;
}

import { findUser } from "./user-service";
import type { User } from "./user-service";

const user: User | undefined = findUser(1);

Import and resolution details

  • import type is erased and avoids a runtime import
  • verbatimModuleSyntax preserves import syntax and requires explicit type imports
  • isolatedModules requires each file to be independently transpilable
  • moduleResolution controls how bare and relative specifiers are resolved
  • Path aliases must be configured in both tsconfig and the bundler or runtime

TypeScript does not rewrite module specifiers by default. If tsconfig maps an alias such as @app/, the bundler, test runner or Node.js loader must understand the same alias. Keeping tsconfig and the runtime resolver aligned prevents imports that type-check but fail at runtime.

Avoid turning a file into a global script unintentionally. If a file has no imports or exports, its top-level declarations share the global scope and can collide with other scripts.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What makes a TypeScript file a module?
  2. 2What does import type change?
  3. 3Why do path aliases need configuration in more than one place?
  4. 4What is isolatedModules?

Say it in the interview

TypeScript follows JavaScript module rules. A file with a top-level import or export is a module with its own scope; without one it is a global script. I use ES modules, mark type-only imports with import type, and keep module resolution aligned between the bundler and tsconfig. That avoids duplicate global declarations and import path surprises.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live TypeScript mock interview and get scored feedback on depth, clarity and confidence.