Modules and type-only imports

Intermediate · 23 min

How TypeScript decides which imports survive compilation, and how import type, isolatedModules, and verbatimModuleSyntax make that explicit.

Before thistsconfig explainedRunning TypeScript without a build step

Michigan TypeScript · 23 min · from 6:36

Modules and type-only imports

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Michigan TypeScriptReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • In TypeScript, any file with a top-level `import` or `export` is a module, and an import can bring in values, types, or both under one name.
  • Types have no runtime existence, so an import used only for types has to disappear from the output. Classic `tsc` does this automatically, which is called import elision.
  • `import type { User }` and the inline form `import { type User, createUser }` mark imports as type-only, so every tool can remove them without looking at any other file.
  • `isolatedModules` reports code that a tool compiling one file at a time can't translate safely, such as re-exporting a type without `export type`.
  • `verbatimModuleSyntax` turns elision off. An import without the `type` keyword stays in the output, an import marked `type` is removed, and the compiler makes you mark every type-only import.

Imports that carry nothing at runtime

The import and export syntax itself is plain JavaScript, covered in ES modules. TypeScript adds one wrinkle: a module can export things that only exist at compile time.

// user.ts
export interface User {
  id: string;
  name: string;
}

export function createUser(name: string): User {
  return { id: crypto.randomUUID(), name };
}
// app.ts
import { User, createUser } from "./user.js";

const u: User = createUser("Ada");
console.log(u.name);

createUser is a real function in the emitted JavaScript. User is not. After the types are removed, user.js has no export called User. If app.js still asked for it, the ES module loader would refuse to link the file. Somebody has to delete User from that import, and the question is who knows enough to do it.

Import elision: tsc cleans up for you

The traditional answer is that the compiler does it. tsc checks every imported name, sees that User is only ever used in type positions, and drops it. Compiled with default settings, app.ts becomes:

import { createUser } from "./user.js";
const u = createUser("Ada");
console.log(u.name);

This is called import elision. It works because tsc sees the whole program and can look inside user.ts to learn that User is an interface.

It has two weaknesses. First, if every name in an import is a type, the whole statement goes, and the module is never loaded. That’s harmless for user.ts, but if the imported module also ran setup code, such as registering a plugin, that setup silently stops. Second, it relies on cross-file knowledge that most modern tools don’t have.

Single-file tools can’t see the other file

esbuild, SWC, Babel, and Node’s type stripping all work one file at a time. That’s why they’re fast. It also means that when they see this line, they have no idea what User is:

export { User } from "./user.js";

Keeping it breaks at runtime if User is an interface. Deleting it breaks things if User is a function. The answer lives in another file.

The isolatedModules flag tells tsc to report exactly these cases, so code that type-checks is also code a single-file tool can translate. With it on, that line produces:

error TS1205: Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.

Saying it yourself: import type

The fix is to write the answer into the current file. TypeScript has two forms:

import type { User } from "./user.js";            // whole statement is type-only
import { type User, createUser } from "./user.js"; // only User is type-only

export type { User } from "./user.js";

A name imported with type can only be used as a type. Try to call it or pass it around as a value and the compiler stops you. In return, any tool can delete it without checking anything else.

The two forms differ in one detail that matters for side effects. import type removes the entire statement. The inline type modifier removes only that name.

verbatimModuleSyntax: no guessing at all

verbatimModuleSyntax, added in TypeScript 5.0, replaces elision with a simpler rule: what you wrote is what you get. Imports and exports without type stay in the output exactly as written. Anything marked type is removed. Nothing else is inferred.

{
  "compilerOptions": {
    "module": "nodenext",
    "verbatimModuleSyntax": true
  }
}

Because the compiler no longer cleans up after you, it makes you be explicit. The original app.ts now fails:

error TS1484: 'User' is a type and must be imported using a type-only import when 'verbatimModuleSyntax' is enabled.

And the two forms now behave predictably:

import type { User } from "./user.js";            // emitted: nothing
import { type User as Alias } from "./user.js";   // emitted: import {} from "./user.js";

The second line keeps an empty import, so user.js still loads and its side effects still run. You can see from the source alone what will be in the output, which is exactly what Node’s type stripping and bundlers need. verbatimModuleSyntax includes the checks isolatedModules does, so you don’t need both. One more consequence: since nothing gets rewritten, import syntax in a file that compiles to CommonJS becomes an error, and you write import x = require("x") there instead.

For new code, turn on verbatimModuleSyntax and let your editor’s quick fix add type where it’s needed. It’s the setting the running TypeScript without a build step lesson recommends for the same reason.

What the video covers

The embed starts at 06:36, where Ian VanSchooten’s Michigan TypeScript talk reaches its “why use type-only imports” chapter. Earlier, the talk opens with a quiz on import errors. From this point it covers why type-only imports matter, enforcing them with the consistent-type-imports ESLint rule, a section on what the TypeScript compiler can do to help, and then side-effect imports and barrel files. It’s a 2023 meetup talk with audience Q&A in the last few minutes. The talk’s own chapter list doesn’t say which compiler flags it shows, so rely on the sections above for exactly how isolatedModules and verbatimModuleSyntax behave. Benny Code’s course in the links is a broader tour of TypeScript import and export forms if you want more practice with the syntax itself.

Check yourself

  1. 01Why can a tool like esbuild or Node's type stripping not tell on its own whether `export { User } from "./user.js"` re-exports a type or a value?

    It only reads one file at a time. Whether `User` is an interface or a function is written in `user.ts`, which it never opens, so it can't know whether to keep or delete the re-export. Writing `export type { User }` puts that answer in the current file.

  2. 02With `verbatimModuleSyntax` on, what is the difference in output between `import type { User } from "./user.js"` and `import { type User } from "./user.js"`?

    The first disappears completely. The second removes `User` but keeps the statement as `import {} from "./user.js"`, so the module is still loaded and any side effects it has still run.

  3. 03Under classic import elision, how can a refactor silently break a program that imports a module only for its types?

    If every name imported from a module is only used as a type, `tsc` drops the whole import statement. Any side effect that module had, like registering a plugin or a global polyfill, stops running, and nothing in the source shows the change.

  4. 04Why is `verbatimModuleSyntax` a good default for new projects?

    It makes the output predictable from the source alone: what you wrote without `type` stays, what you marked `type` goes. That is exactly the rule single-file tools follow, so the code behaves the same under `tsc`, a bundler, or Node's type stripping.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark