Intermediate · 16 of 16 · 12 min read
Modules and import type
Why a file with no import or export is global, what import type guarantees about the emit, and the alias that type-checks and then fails at runtime.
- Modules
TypeScript uses the ES module system and adds one question JavaScript never had: is this import a value that must survive into the output, or a type that must not?
Script or module
// a.ts — no import, no export: this is a *script*
interface User { id: number }
// b.ts — also a script
interface User { name: string }
// Both are global, so they merge. `User` is now { id: number; name: string },
// and nothing told you.
One export fixes it:
// a.ts
export interface User { id: number }
// b.ts
export interface User { name: string } // a different, unrelated User
When a file genuinely has nothing to export, export {} is the idiom that makes it a module
anyway. The moduleDetection: "force" option does the same thing project-wide, and is worth
turning on.
// side-effects.ts
console.log("ready");
export {}; // scoped, not global
import type
import type { User } from "./user"; // always erased
import { createUser } from "./user"; // kept — it is a value
import { type Role, hasRole } from "./roles"; // inline type modifier
import "./polyfills"; // kept, for the side effect
declare const u: User;
console.log(typeof createUser, typeof hasRole, u);
The guarantee is about the output. A import type never appears in the emitted JavaScript, so
it can never cause a module to be evaluated and never adds a runtime dependency. That matters in
three places: avoiding a circular import at runtime, keeping a dev-only package out of the bundle,
and making the emit predictable for a single-file transpiler.
Exports work the same way:
export type { User };
export { type Role, hasRole };
declare const hasRole: () => boolean;
interface User { id: number }
type Role = string;
verbatimModuleSyntax
Without it, the compiler decides whether to drop an import based on whether it ended up being used as a value. That is a whole-program question, which a file-by-file transpiler cannot answer — so the two disagree, and whether a module’s side effects run becomes accidental.
// With verbatimModuleSyntax, you have to say which it is:
import type { Config } from "./config"; // erased, guaranteed
import { DEFAULTS } from "./config"; // kept, guaranteed
declare const c: Config;
console.log(DEFAULTS, c);
Its companion is isolatedModules, which rejects anything else that cannot be transpiled one file
at a time:
// Rejected under isolatedModules — is `User` a type or a value?
// export { User } from "./user";
export type { User } from "./user"; // unambiguous
// const enum Direction { Up } // also rejected — needs cross-file inlining
| Form | In the emit |
|---|---|
import { X } from "m" |
kept if X is used as a value, dropped otherwise |
import type { X } from "m" |
never |
import { type X, y } from "m" |
the module is kept, X is not |
import "m" |
always, for the side effect |
import * as m from "m" |
kept |
Default and named exports
// user.ts
export interface User { id: number }
export function createUser(id: number): User { return { id }; }
export default createUser;
// app.ts
// import createUser, { type User, createUser as named } from "./user";
The same advice as in JavaScript applies, and TypeScript sharpens it: a named export is checked
against its name, so a typo is a build error, while a default can be imported under any name at
all. Named exports also let import type do its job per-symbol.
Resolution, and the trap
{
"compilerOptions": {
"baseUrl": ".",
"paths": { "@lib/*": ["src/lib/*"] }
}
}
paths tells the compiler how to resolve @lib/thing. It does not rewrite the import, so the
emitted JavaScript still says @lib/thing — and the bundler, the test runner and Node each need
the same alias configured separately or it fails at runtime.
That is the most common “it type-checks and then crashes” in TypeScript. The alternative that
needs no duplication is the imports field in package.json, which Node and most bundlers
understand natively:
{
"imports": {
"#lib/*": "./src/lib/*.js"
}
}
moduleResolution is the other half of resolution, and in a modern project it should be
"bundler" or "nodenext" — the older "node" setting models Node 10 and gets extensions and
exports maps wrong.
Extensions
Under nodenext, a relative import needs the extension of the output file, which is .js
even from a .ts source:
// Correct under nodenext, however odd it looks:
// import { createUser } from "./user.js";
// Correct under moduleResolution: "bundler":
// import { createUser } from "./user";
export {};
It reads strangely and it is right: the compiler does not rewrite specifiers, so what you write is what the runtime resolves.
Circular imports
Types are erased, so a cycle that exists only in the types is harmless — which is precisely what
import type lets you express:
// user.ts
import type { Order } from "./order";
export interface User { id: number; orders: Order[] }
// order.ts
import type { User } from "./user";
export interface Order { id: number; user: User }
Neither file imports the other at runtime, so there is no cycle to resolve. The same two files with value imports would produce one, with the usual partially-initialised-module symptoms.
Common mistakes
A declaration file that is accidentally a script
Mistake. declare module "x" { … } in a file with no imports or exports.
Why it fails. Without an import the file is a script, so declare module declares a new
ambient module rather than augmenting the real one — and the real one’s types disappear.
What to do instead. import type something from it, or add export {}.
Adding paths and nothing else
Mistake. Configuring an alias in the tsconfig and importing from it.
Why it fails. paths is compiler-only; the emitted import is unchanged.
What to do instead. Mirror it in the bundler and the test runner, or use package.json
imports.
A plain import for something used only as a type
Mistake. import { User } from "./user" where User is an interface.
Why it fails. Mostly nothing — until verbatimModuleSyntax is turned on, or until the import
pulls a module with side effects into a bundle that did not need it.
What to do instead. import type, and let the lint rule enforce it.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
What does import type { User } from "./user" guarantee?
A file with no imports or exports is not a module, and its declarations are global.
Why do two files that each declare interface User conflict?
// a.ts
interface User { id: number }
// b.ts
interface User { name: string }What do paths in a tsconfig do, and what do they not do?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.