The compiler as a system
Relay’s worker package type-checks and runs under Bun. A teammate runs the same file with Node 24 and gets
ERR_MODULE_NOT_FOUND: Cannot find module '.../job'. Nothing was wrong with the types. The imports were written
without file extensions, which moduleResolution: "bundler" accepts and Node’s ES module loader does not. tsc
had been told to resolve like a bundler, so it said nothing.
The checker is one stage of a pipeline: find the files, resolve each import, check, then emit or strip. Each stage has
settings that change what the others accept. This lesson walks the pipeline with the options that matter, and
every behavior below comes from running tsc 7.0.2, the native compiler this course uses. Where the browser
playground (TypeScript 5.9) differs, the lesson says so.
What module and moduleResolution decide
Section titled “What module and moduleResolution decide”moduleResolution says how a specifier such as "./job" or "dual/sub" becomes a file. tsc --help --all lists three
values in TypeScript 7: node16, nodenext and bundler. The old node10 and classic are gone (see below).
By default, nodenext follows module: nodenext, node16 follows module: node16 or node18, and everything else is
bundler.
The two families work from different premises:
bundlerassumes something downstream, such as Bun, Vite or esbuild, resolves the import. Extensionless relative imports work, and so do directory imports.package.jsonexportsare still read.nodenextassumes Node resolves it at runtime, so it copies Node’s rules. A.tsfile is an ES module or a CommonJS module depending on its extension (.mts,.cts) and the nearestpackage.json"type". In an ES module, relative imports need an explicit extension and directory imports are not allowed.
A probe of both, with rel.ts containing import { u } from "./util":
tsc --noEmit --ignoreConfig --module esnext --moduleResolution bundler rel.ts # no output: acceptedtsc --noEmit --ignoreConfig --module nodenext rel.ts # in a package with "type": "module"rel.ts(1,19): error TS2835: Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Did you mean './util.js'?The same file in a package without "type": "module" passes under nodenext, because it is a CommonJS file and
require("./util") has no extension rule. The format comes from package.json, which is why moving a package from CommonJS to
ES modules turns working imports into errors. A directory import, ./lib for ./lib/index.ts, gets TS2834 under
nodenext and passes under bundler.
Relay’s rule: if the code runs on Node, or might, check it with nodenext. If Bun or a bundler is the only runtime
you will ever have, bundler is honest. The unsafe choice is bundler for code that Node also runs.
Extensions: .ts, .js and the emit rule
Section titled “Extensions: .ts, .js and the emit rule”Node loads files by their real name, so the import must name a file that exists after the build. There are two
conventions, and tsc 7 supports both:
- Write
.js, the output name.import "./util.js"resolves toutil.tsin the editor, and the emitted file is correct without rewriting. I ran this undernodenextand it passed. - Write
.ts, the source name. That needsallowImportingTsExtensions, and without it you getTS5097. Because an emitted.jsfile would still say./util.ts, the flag is only allowed withnoEmit,emitDeclarationOnly, orrewriteRelativeImportExtensions:
error TS5096: Option 'allowImportingTsExtensions' can only be used when one of 'noEmit', 'emitDeclarationOnly', or 'rewriteRelativeImportExtensions' is set.rewriteRelativeImportExtensions is the option for emitting JavaScript from .ts specifiers: tsc rewrote
./util.ts to ./util.js in the output. It does not rewrite a specifier that crosses a project boundary. See
project references, below.
exports, imports and conditions
Section titled “exports, imports and conditions”Under nodenext, a package’s exports map decides what can be imported, and its conditions decide which file
you get. I made a package dual with . mapped to import and require conditions, each with its own types, plus a ./sub
entry. Then I imported it from an ES module and from a .cts file:
{ "name": "dual", "exports": { ".": { "import": { "types": "./esm.d.ts", "default": "./esm.js" }, "require": { "types": "./cjs.d.cts", "default": "./cjs.cjs" } }, "./sub": { "types": "./sub.d.ts", "default": "./sub.js" } }}# e.ts is an ES module, c.cts is CommonJS; both import { flavor } from "dual", declared "esm" and "cjs"c.cts(3,14): error TS2322: Type '"cjs"' is not assignable to type '"esm"'.e.ts(2,14): error TS2322: Type '"esm"' is not assignable to type '"cjs"'.Each file saw the declaration its own format selects: the ES module got the import condition’s esm and the
.cts file got require’s cjs. That is the dual-package hazard made visible: one specifier, two type worlds.
dual/hidden, a file that exists in the package but is not in exports, failed with TS2307 in every mode I tried, including bundler. Files an
exports map does not list are private. A package.json imports field ("#util": "./util.ts") resolved correctly under nodenext.
The four Node-flavored module values differ in one rule I could observe. A CommonJS file that imports an ES module
statically is an error under node16 and node18 (TS1479), and accepted under node20 and nodenext, which model
Node versions that can require() an ES module. The playground cannot do this experiment, but the lesson’s check is
simple: pick the value that matches the lowest Node version you ship to.
verbatimModuleSyntax and what imports become
Section titled “verbatimModuleSyntax and what imports become”Without the flag, tsc decides which imports to keep. An import used only as a type, or unused, is elided. I
compiled import { job } from "./job.ts" where job was never used:
# defaultexport const z = 1;# --verbatimModuleSyntaximport { job } from "./job.js";export const z = 1;With the flag, what you write is what is emitted, so an import that is only a type has to say so. Otherwise a tool
that compiles one file at a time (Bun, esbuild, Node’s stripper) cannot know whether Job is a type:
// @ts-expect-error: 'PathLike' is a type and must be imported using a type-only importimport { PathLike, readFileSync } from "node:fs"
export const read = (path: PathLike): Buffer => readFileSync(path)The error was TS1484 here. For re-exports the matching rule belongs to isolatedModules: import { Job } followed by
export { Job } fails with TS1205: Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.
isolatedModules makes the compiler reject code that only works when it can see other files. It is the
promise that any single-file transpiler can handle your file. Its sibling for declaration files,
isolatedDeclarations, is covered in Publishing typed packages.
Type stripping and erasable syntax
Section titled “Type stripping and erasable syntax”Node 24 runs .ts files directly by deleting the type annotations and changing nothing else. Bun transpiles more, since it runs enums and namespaces, but Node and
other strippers do not. The deletion only works if every piece of TypeScript syntax can be removed
without generating code. erasableSyntaxOnly makes tsc reject syntax that cannot. I ran it over a file with each construct:
node enum.ts # enum E { A }; console.log(E.A)SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript enum is not supported in strip-only modeWith tsc 7.0.2, --erasableSyntaxOnly reported TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled on exactly these:
enum, const enum, a namespace that contains values, parameter properties (constructor(private name: string)),
import x = require(...), export =, and the angle-bracket assertion <number>x. It accepted a namespace that
holds only types, declare namespace, declare enum, abstract classes and private fields, because those leave nothing behind.
Each non-erasable construct has an erasable version. Here are the three Relay used:
export enum Level { Debug, Info}
export namespace Retry { export const max = 3 export function delay(attempt: number): number { return attempt * 100 }}
export class Worker { constructor( private readonly name: string, public attempts = 0 ) {}}export const Level = { Debug: 0, Info: 1 } as constexport type Level = (typeof Level)[keyof typeof Level]
export const max = 3export function delay(attempt: number): number { return attempt * 100}
export class Worker { private readonly name: string attempts: number
constructor(name: string, attempts = 0) { this.name = name this.attempts = attempts }}The object plus a type with the same name is the standard enum replacement. It is a value and a type, can be iterated
with Object.values, and has no reverse mapping to surprise you. A namespace becomes a module, with import * as Retry at the
call site. Parameter properties become two lines of explicit assignment.
Project references and tsc -b
Section titled “Project references and tsc -b”One tsconfig.json checks one program. A monorepo with core and app packages wants app to see core’s
declarations and not recheck its source. composite plus references does that, and tsc -b (build mode) builds the
graph in dependency order. I built two such projects with tsc 7 and used the following:
{ "extends": "../tsconfig.base.json", "compilerOptions": { "composite": true, "rootDir": "src", "outDir": "dist" }, "include": ["src"], "references": [{ "path": "../core" }]}tsc -b -vThe first build wrote core/dist/job.js and job.d.ts, app/dist/main.js and main.d.ts, and one tsconfig.tsbuildinfo next to each
tsconfig.json. Then I changed only a function body in core. -v showed core rebuilding and app as
up to date with .d.ts files from its dependencies, so the app project was not re-checked. That is the payoff:
a declaration did not change, so nothing downstream needs to. tsc -b --clean deleted both outputs and buildinfo files.
Two failures to know:
- Remove the
referencesentry andappcannot importcore’s source:TS6059(file not underrootDir) andTS6307(not listed in the project’s file list). - With
rewriteRelativeImportExtensionson, a relative.tsimport that crosses into another project givesTS2878: This import path is unsafe to rewrite. I used a.jsspecifier there.
What TypeScript 7 changes
Section titled “What TypeScript 7 changes”The compiler is a native program written in Go. node_modules/typescript now holds a small launcher, bin/tsc,
that finds the binary for your platform (here, the @typescript/typescript-darwin-arm64 package) and runs it. The
speed comes from native code and parallel checking. For a measured number on this site’s exercise project, tsc -p src/exercises --extendedDiagnostics
reported 458 files and 172,364 lines (mostly the standard library and @types), with a check time of 0.112 s and a total time of 0.191 s on the
author’s machine. That is one data point, not a benchmark. --checkers, --builders and --singleThreaded are real flags in the help output.
The JavaScript compiler API is not there. require("typescript") returns only version and versionMajorMinor, and
createProgram is undefined. Tools that used to import the compiler need a different route. The package ships typescript/unstable/sync
and typescript/unstable/async entry points, and their name says what to expect: importing the first one gave API, Checker, Emitter and similar exports.
Do not build on those without pinning the version. TypeScript 7.0 ships no stable API; the 7.0 announcement says 7.1 is expected to add a new one. Until then, the @typescript/typescript6 package re-exports the 6.0 API (with a tsc6 binary) for tools that need it.
Most of these options were deprecated in TypeScript 6.0 (silenced there with ignoreDeprecations: "6.0") and are removed in 7.0. This table is what tsc 7.0.2 printed when I passed each one:
| Option | Result |
|---|---|
--target es5 |
TS5108: Option 'target=ES5' has been removed |
--moduleResolution node10 (or node), classic |
TS5108 ... has been removed |
--module amd, umd, system |
TS5108 ... has been removed |
--baseUrl, --outFile, --downlevelIteration |
TS5102: Option '...' has been removed |
--esModuleInterop false, --allowSyntheticDefaultImports false, --alwaysStrict false |
TS5108 ... has been removed |
--importsNotUsedAsValues, --preserveValueImports, --keyofStringsOnly, --charset, --out |
TS5023: Unknown compiler option |
The defaults changed in 6.0 and carry into 7. In a project with no settings, tsc 7 reported TS7006 for an untyped parameter, so
strict is on by default. tsc --help --all gives the target default as es2025 and esModuleInterop as true.
The types default is empty: a global declared in node_modules/@types/foo was not found until I passed --types foo. The tsc --init template for 7.0.2
writes, among others, module: nodenext, target: esnext, types: [], strict, noUncheckedIndexedAccess, exactOptionalPropertyTypes, verbatimModuleSyntax,
isolatedModules and moduleDetection: force, so the course’s strict config is close to what a new project now starts with.
The practical rule
Section titled “The practical rule”Decide where the code runs, then say so in the config. Code that Node might run: module: nodenext, real extensions,
verbatimModuleSyntax and erasableSyntaxOnly. Then the same files run under Node’s stripper, Bun and a bundler. Code that only a bundler
sees can use bundler, and you lose nothing until the day another runtime loads it. Do not use project references for a single
package: they add build steps, composite constraints and a second mental model, and pay off only when a graph is slow to re-check.
Exercise
Section titled “Exercise”This is a local exercise. Create a folder in the Relay project from M1’s tooling lesson, such as
packages/worker/. Copy in package.json, job.ts, the four *.starter.ts files renamed without .starter
(status.ts, queue.ts, worker.ts, main.ts), tsconfig.relay.starter.json renamed to tsconfig.relay.json, and the test.
Then run bun test.
The package runs under Bun but fails every check that matters for Node. You edit the four source files and the
config. Make the config use module: nodenext and erasableSyntaxOnly, so the files pass tsc, rewrite the enum, namespace and
parameter properties, and fix the imports. The tests run tsc over the package and run bun main.ts, so
typescript has to be installed in the project. Run bunx tsc -p tsconfig.relay.json yourself to read the errors.
{ "name": "relay-worker", "private": true, "type": "module"}{ "compilerOptions": { "target": "esnext", "module": "esnext", "moduleResolution": "bundler", "strict": true, "noEmit": true, "skipLibCheck": true }, "files": ["main.ts"]}export interface Job { readonly id: string readonly kind: string}export enum JobStatus { Queued, Running, Done}import { Job } from "./job"
export namespace Queue { const waiting: Job[] = []
export function push(job: Job): number { return waiting.push(job) }
export function shift(): Job | undefined { return waiting.shift() }}import { Job } from "./job"import { JobStatus } from "./status"
export class Worker { constructor( private readonly name: string, public status: JobStatus = JobStatus.Queued ) {}
start(job: Job): string { this.status = JobStatus.Running return `${this.name} ran ${job.id}` }}// Relay's worker package runs fine under Bun, but it is not ready for Node's type stripping or for `module: nodenext`.// Make it ready. Copy these files next to package.json and run `bun test`.//// Rules:// - tsconfig.relay.json sets `module` to "nodenext" and turns on `erasableSyntaxOnly`.// - No enum, no namespace with values, no parameter properties: every file passes `tsc --erasableSyntaxOnly`.// - Relative imports name the real file, including the `.ts` extension, and type-only imports say `type`.// - JobStatus stays usable as both a value and a type, and its values are the strings "queued", "running" and "done".// - `bun main.ts` prints the same log as before, with the status as a string.import { Job } from "./job"import { JobStatus } from "./status"import { Queue } from "./queue"import { Worker } from "./worker"
const jobs: Job[] = [ { id: "job_1", kind: "email.send" }, { id: "job_2", kind: "webhook.deliver" }]
for (const job of jobs) Queue.push(job)
const worker = new Worker("w1")const log: string[] = []for (let next = Queue.shift(); next !== undefined; next = Queue.shift()) log.push(worker.start(next))worker.status = JobStatus.Done
console.log(JSON.stringify({ log, status: worker.status }))import { expect, test } from "bun:test"import { existsSync } from "node:fs"import { join } from "node:path"import { JobStatus } from "./status.ts"
const tsc = [join(import.meta.dir, "../../../node_modules/.bin/tsc"), join(process.cwd(), "node_modules/.bin/tsc")].find(existsSync) ?? "tsc"
function run(cmd: string[]): { code: number; out: string } { const r = Bun.spawnSync(cmd, { cwd: import.meta.dir }) return { code: r.exitCode, out: r.stdout.toString() + r.stderr.toString() }}
test("tsconfig.relay.json resolves modules like Node and bans syntax that needs a transform", () => { const shown = run([tsc, "--showConfig", "-p", "tsconfig.relay.json"]) expect(shown.code).toBe(0) const options = JSON.parse(shown.out).compilerOptions expect(options.module).toBe("nodenext") expect(options.erasableSyntaxOnly).toBe(true)})
test("the package type-checks under its own tsconfig", () => { const checked = run([tsc, "-p", "tsconfig.relay.json"]) expect(checked.out).toBe("") expect(checked.code).toBe(0)})
test("the sources are erasable and resolve under nodenext whatever the tsconfig says", () => { const checked = run([ tsc, "--ignoreConfig", "--noEmit", "--strict", "--target", "esnext", "--module", "nodenext", "--erasableSyntaxOnly", "--allowImportingTsExtensions", "--verbatimModuleSyntax", "main.ts" ]) expect(checked.out).toBe("") expect(checked.code).toBe(0)})
test("bun runs the package and the status is a string", () => { const ran = run([process.execPath, "main.ts"]) expect(ran.code).toBe(0) expect(JSON.parse(ran.out)).toEqual({ log: ["w1 ran job_1", "w1 ran job_2"], status: "done" })})
test("JobStatus is a plain object of strings", () => { expect(JobStatus).toEqual({ Queued: "queued", Running: "running", Done: "done" })})moduleResolution: bundleraccepts what a bundler would.nodenextcopies Node: extensions are required in ES modules, and the format of each file comes from its extension andpackage.json..tsspecifiers needallowImportingTsExtensions, which only works withnoEmit,emitDeclarationOnlyorrewriteRelativeImportExtensions.exportsconditions give an ES module and a CommonJS file different declarations from one specifier. Files not listed are private.verbatimModuleSyntaxkeeps imports as written, so type-only imports must saytype.erasableSyntaxOnlyrejects enums, namespaces with values, parameter properties,import =,export =and angle-bracket assertions. Each has a plain replacement.tsc -bwithcompositeandreferencesskips downstream projects when a dependency’s declarations did not change.- TypeScript 7 is a native binary with no JavaScript compiler API, several removed options, and
stricton by default.
Further reading
Section titled “Further reading”- Announcing TypeScript 7.0: the native port, the missing API and the
@typescript/typescript6package. - Announcing TypeScript 6.0: the new defaults and the deprecated options.
- TypeScript 5.8: The –erasableSyntaxOnly Option: what the flag rejects and how it pairs with Node.
- Modules: TypeScript: what Node’s type stripping supports.