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:
- First, it looks for
utils.ts - Then
utils.tsx(if applicable) - Then
utils.d.ts(type declaration files) - 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.jsactually exists - The runtime executes successfully
The Extension Priority Order
TypeScript searches in this order:
.ts.tsx.d.ts.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.