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

Extension Resolution: .ts vs .js

Why TypeScript looks for .ts, .tsx, .d.ts files even when you import .js paths.

Extension Resolution: .ts vs .js

You'll learn: Why TypeScript looks for .ts, .tsx, and .d.ts files even when you write .js extensions in your imports.

The Discrepancy Between Import and Reality

When you import a TypeScript module, something peculiar happens. You might write:

import { helper } from './utils.js';

Notice you're importing from ./utils.js — but TypeScript actually finds and type-checks ./utils.ts! This seems contradictory at first, but it's a deliberate design decision that solves a critical problem.

Why This Matters

TypeScript is a compile-time tool. Your source code contains .ts files, but after compilation, you ship .js files. The module resolution system needs to bridge this gap.

When you write an import path, TypeScript asks: "What file do I need to check right now?" Meanwhile, the JavaScript runtime later asks: "What file do I need to load when this code runs?"

TypeScript's resolver handles this by performing extension substitution during type checking. When it sees ./utils.js in your import:

  1. First, it looks for utils.ts
  2. Then utils.tsx (if applicable)
  3. Then utils.d.ts (type declaration files)
  4. Only finally would it consider an actual utils.js

The Module Output Paradox

Think of it like writing directions for a building that's still under construction. You reference the blueprint (.ts) now, but know the final building (.js) will exist when people need it.

Your TypeScript imports point to .js extensions because that's what will exist after compilation. But during type-checking, TypeScript intelligently substitutes those extensions to find your source files.

This means:

  • You can write import './file.js' in TypeScript
  • TypeScript finds and checks file.ts
  • After compilation, file.js actually exists
  • The runtime executes successfully

The Extension Priority Order

TypeScript searches in this order:

  1. .ts
  2. .tsx
  3. .d.ts
  4. .js (with type information if available)

This priority system ensures TypeScript always finds the most type-rich source first.

Key Takeaway: TypeScript's module resolver translates .js extensions in imports to .ts extensions during type-checking, allowing you to write runtime-correct import paths while still checking against TypeScript source files. This bridging behavior makes TypeScript's compile-to-JavaScript workflow seamless.