Advanced · 12 of 12 · 13 min read
The compiler and the build
What tsc does and does not do in a modern toolchain, the options that change program meaning rather than output, and why type-checking and transpiling are now separate jobs.
- tsconfig
- Tooling
tsc does two separable jobs: it checks types and it emits JavaScript. In a modern toolchain
something else almost always does the second one — and understanding that split explains most
build configuration.
Who does what
| Tool | Checks types | Emits JS | Notes |
|---|---|---|---|
tsc |
yes | yes | the only one that checks |
tsc --noEmit |
yes | no | the CI gate |
| esbuild / Vite | no | yes | per-file transpile, very fast |
| SWC / Next.js | no | yes | same model |
| Babel + preset-typescript | no | yes | same model |
tsc --build |
yes | yes | project references, incremental |
Every row that says “no” transpiles one file at a time with no cross-file knowledge. That is
why it is fast and why it imposes isolatedModules rules: a const enum needs inlining across
files, and whether import { X } is a type or a value cannot be answered from one file.
{
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"typecheck": "tsc --noEmit"
}
}
The && is the whole point: the bundler would happily ship code with type errors in it.
target, lib and module
Routinely conflated, and they answer three different questions:
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler"
}
}
target— which syntax to emit.ES5downlevelsasync/awaitinto a state machine;ES2022leaves it alone.lib— which APIs the compiler believes exist. It defaults fromtarget, and overriding it is how you say “modern syntax, but this runtime has no DOM” (or the reverse: an older target with a polyfilledArray.prototype.at).module— which module syntax to emit:ESNextkeepsimport,CommonJSrewrites torequire.moduleResolution— how specifiers are looked up.bundlerfor a bundled app,nodenextfor code Node runs directly. The oldnodevalue models Node 10 and getsexportsmaps wrong.
The common mistake is reaching for target when the problem is lib:
// `target: "ES5"` with a polyfill loaded — the syntax is fine, the API is missing.
// Object.fromEntries does not exist on type 'ObjectConstructor'
// Adding "ES2019" to `lib` tells the compiler it is there.
const entries: Array<[string, number]> = [["a", 1]];
console.log(Object.fromEntries(entries));
lib is a claim about the runtime, exactly like a declaration file, and nothing verifies it.
The options that change what your code means
Most of tsconfig.json is about output. A handful change whether a program is valid at all, and
these are the ones worth knowing by name:
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"verbatimModuleSyntax": true,
"isolatedModules": true,
"noImplicitOverride": true,
"noFallthroughCasesInSwitch": true,
"erasableSyntaxOnly": true
}
}
strict is eight checks in one flag, and the two below it are the ones strict deliberately does
not include because they are noisy in existing code:
const items = ["a", "b"];
const first = items[0]; // string — with noUncheckedIndexedAccess: string | undefined
console.log(first?.toUpperCase());
interface Options { timeout?: number }
// With exactOptionalPropertyTypes, this is an error:
// const o: Options = { timeout: undefined };
// "absent" and "present but undefined" stop being the same thing.
const o: Options = {};
console.log(o.timeout);
noUncheckedIndexedAccess is the highest-value non-strict flag in most codebases: array and index
access is the single biggest source of runtime undefined that strict alone lets through.
erasableSyntaxOnly (TypeScript 5.8) rejects the TypeScript-only constructs that cannot be
removed by stripping — enums, namespaces with values, parameter properties — which is what Node’s
own type stripping requires.
Compile speed
Three measurements before three fixes, in order of how often they help:
{
"compilerOptions": {
"skipLibCheck": true,
"incremental": true,
"tsBuildInfoFile": "./node_modules/.cache/tsbuildinfo"
},
"include": ["src"],
"exclude": ["dist", "**/*.test.ts"]
}
skipLibCheck: true— stop type-checking.d.tsfiles innode_modules. Nearly always correct: those errors are not yours to fix, and checking them is a large fraction of a cold build.incremental: true— reuse the previous program. Cheap, and the build-info file belongs in a cache directory, not indist.- A narrow
include— the default sweeps every.tsunder the project root, which on a monorepo can mean checking other packages’ sources twice.
Then the diagnostics, which say where the time actually goes:
# Where the time goes
tsc --noEmit --extendedDiagnostics
# Which types are expensive to check
tsc --noEmit --generateTrace trace
--extendedDiagnostics prints check time, memory and instantiation counts; a very large
“Instantiations” number points at a type-level computation, usually a template literal cross
product or a deep recursive conditional.
Project references
For a monorepo, references turn one giant program into a graph of independently built ones:
{
"files": [],
"references": [
{ "path": "./packages/core" },
{ "path": "./packages/web" }
]
}
Each referenced project sets "composite": true, emits declarations, and is rebuilt only when its
own inputs change. tsc --build walks the graph in dependency order and skips what is up to date.
The payoff is real on a large repo; on a single application it is pure overhead, and the simpler
answer is one tsconfig with a narrow include.
Config inheritance
{
"extends": "./tsconfig.base.json",
"compilerOptions": {
"noEmit": true
},
"include": ["src", "tests"]
}
One base with the strictness settings, one small file per package or per tool. Two details worth
remembering: relative paths in the inherited file resolve against the file that declared them,
not the one extending it; and files/include/exclude are replaced wholesale rather than
merged, which is the usual surprise.
The community base configs (@tsconfig/node22, @tsconfig/strictest) are a reasonable starting
point and encode exactly the decisions above.
What survives compilation
Worth being able to state precisely, because it is the premise of half the questions in this track:
| Written | After compilation |
|---|---|
| Type annotations, interfaces, type aliases | gone |
| Generics | gone — one function, no specialisation |
private / protected |
gone (the property remains, readable) |
#private |
kept — real JavaScript |
enum |
kept — an object is emitted |
const enum |
inlined at each use (needs whole-program knowledge) |
namespace with values |
kept — an IIFE |
| Parameter properties | kept — assignments in the constructor |
| Decorators | kept — function calls |
emitDecoratorMetadata types |
kept — the one place types become runtime data |
The entries in the “kept” column are exactly the ones erasableSyntaxOnly and a stripping-only
runtime disallow. If you want code that Node can run directly with no build step, avoid them.
Common mistakes
Assuming the bundler checks types
Mistake. A CI pipeline whose only TypeScript step is vite build.
Why it fails. esbuild and SWC strip types without checking them; the build succeeds with type
errors in it.
What to do instead. tsc --noEmit as its own CI step, and in the build script before the
bundler.
Changing target to get a missing API
Mistake. Raising target because Object.fromEntries or String.replaceAll is not found.
Why it fails. target controls emitted syntax; the missing declaration comes from lib. The
change ships different syntax to solve a type problem.
What to do instead. Add the library to lib, and keep target matched to what the runtime
actually supports.
paths without the matching runtime alias
Mistake. Adding an alias to the tsconfig and importing from it.
Why it fails. paths only teaches the compiler; the emitted import is unchanged, so the
bundler, Node and the test runner each need the same alias or it fails at runtime.
What to do instead. Mirror it in every tool, or use the imports field in package.json,
which they all understand.
Check yourself
4 questions from the bank on what you just read. Answering here does not affect your quiz history.
Why do most projects type-check with tsc but build with something else?
What does isolatedModules enforce, and why?
What are TypeScript project references for?
A type error that only appears in CI usually means two different checkers disagree.
The editor is clean but tsc --noEmit fails in CI. What is the usual cause?
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.