Sub topic 10
Controlling what tsc emits
This chapter assumes you can run tsc with a tsconfig.json, and that you know the compiler checks types and then erases them to produce JavaScript. Here you will learn which options decide whether tsc writes files, which files it writes, and how to avoid the usual mistakes.
Emit is separate from checking
By default, tsc writes JavaScript even when type errors are found. The type checker reports errors, the emitter still runs, and the process exits with a non-zero status. Exit code 2 means errors were reported and output was generated. Exit code 1 means errors were reported and output was skipped. Exit code 0 means no errors.
This default surprises many people. A build can print red errors and still leave a fresh dist/index.js behind. A deploy script that only checks for the existence of that file would ship code that does not type-check.
Take a small project with this file in src/index.ts:
export function double(n: number): number {
return n * 2;
}
const label: string = double(21);
console.log(label);Compile it with this tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"]
}npx tsc
echo "exit code: $?"
ls disttsc reports error TS2322: Type 'number' is not assignable to type 'string', exits with code 2, and ls dist still lists index.js. The emitter does not need correct types, because it only removes annotations.
noEmitOnError: refuse to write broken builds
Set noEmitOnError to true to make tsc skip all output whenever any error is found.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"rootDir": "src",
"outDir": "dist",
"noEmitOnError": true
},
"include": ["src"]
}With the broken src/index.ts above, npx tsc now exits with code 1 and writes nothing.
Keep these points in mind:
- The option is all-or-nothing. One error in any file in the program blocks output for every file.
- An old
distfrom a previous successful build stays on disk. A blocked build does not delete it, so you may run stale code without noticing. - In watch mode, the check runs on each rebuild. When you fix the error, the next rebuild writes the files.
For local development, many people leave noEmitOnError off so they can run partly broken code while iterating. For release builds, turn it on.
noEmit: type-check only
noEmit: true runs the full type check and writes nothing. It is the right setting in three common cases:
- CI and pre-commit checks. You want a pass or fail answer, not files.
- A bundler or runner produces the JavaScript. Tools such as esbuild, Vite, or a TypeScript-aware runner strip types themselves.
tscthen only supplies the checking they skip. - Editors and scripts that import
.tsfiles directly. The optionallowImportingTsExtensionsis only allowed together withnoEmitoremitDeclarationOnly, becausetsccannot rewrite those import paths in emitted output.
You can set it in the config file or on the command line:
npx tsc --noEmitnoEmit also works with incremental builds. With incremental: true, tsc writes only a small .tsbuildinfo cache file, which makes repeated checks faster. Set tsBuildInfoFile to choose where the cache goes.
{
"compilerOptions": {
"noEmit": true,
"incremental": true,
"tsBuildInfoFile": "./.cache/tsc.tsbuildinfo"
}
}One base config, two uses
A frequent pattern is a base tsconfig.json that does not emit, and a second config used only for real builds. The base file is what your editor and your typecheck script read.
tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"rootDir": "src",
"outDir": "dist",
"noEmit": true
},
"include": ["src"]
}tsconfig.build.json:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"noEmit": false,
"noEmitOnError": true,
"sourceMap": true,
"declaration": true
},
"exclude": ["src/**/*.test.ts"]
}package.json scripts:
{
"scripts": {
"typecheck": "tsc --noEmit",
"build": "tsc -p tsconfig.build.json",
"dev": "tsc -p tsconfig.build.json --watch --preserveWatchOutput"
}
}The child config overrides noEmit and inherits the rest. Note that exclude in the child replaces the parent's exclude rather than merging with it. Relative paths such as include resolve against the config file where they were written, which matters once configs live in different folders.
Source maps: debugging the original TypeScript
Emitted JavaScript differs from your source. Line numbers shift, and newer syntax may be rewritten for the target. A source map is a JSON file that links each position in the output back to the original .ts file. Debuggers and stack-trace tools use it.
Turn it on with sourceMap:
{
"compilerOptions": {
"outDir": "dist",
"sourceMap": true
}
}After a build, dist/index.js ends with the comment //# sourceMappingURL=index.js.map, and dist/index.js.map sits beside it. Related options:
| Option | Effect | Typical use |
|---|---|---|
| `sourceMap` | Writes a separate `.js.map` file per output file | Node services, browsers |
| `inlineSourceMap` | Embeds the map in the `.js` file as a data URL | Single-file output, test runners |
| `inlineSources` | Embeds the original TypeScript text in the map | Debugging where the `.ts` files are not deployed |
| `sourceRoot` | Sets the base location debuggers use to find sources | Maps served from a different host |
Do not combine sourceMap with inlineSourceMap. The compiler rejects that pairing.
Node.js ignores source maps in stack traces unless you ask for them:
node --enable-source-maps dist/index.jsWithout that flag, an uncaught error points to lines in dist/index.js, not src/index.ts.
Declaration output
A declaration file (.d.ts) describes the types of a module without its implementation. If your project is a library, consumers need these files to get types.
declaration: truewrites a.d.tsfile next to each.jsfile.declarationMap: trueadds maps so an editor's "go to definition" jumps to your.tssource instead of the.d.ts.emitDeclarationOnly: truewrites only declaration files. Use it when a bundler produces the JavaScript and you still want to publish types.
Applications that nobody imports as a package rarely need declarations.
Choosing where output goes
Two options decide the shape of the output folder:
outDiris the root folder for all emitted files.rootDiris the folder thattsctreats as the root of the source tree. The folder structure below it is copied intooutDir.
If you omit rootDir, tsc infers it from the common ancestor of your input files. That can change silently. Adding one file outside src, such as scripts/seed.ts, moves the inferred root up one level, and your output becomes dist/src/index.js. Setting rootDir explicitly turns that situation into an error instead of a surprise.
Two further facts help when debugging:
tscnever deletes files. If you renameold.tstonew.ts,dist/old.jsstays. Remove the output folder before a release build, withrm -rf distor a cross-platform tool such asrimraf.npx tsc --listEmittedFilesprints every file written, andnpx tsc --showConfigprints the final merged configuration, including values inherited throughextends.
Other options that affect output
removeCommentsdrops comments from the JavaScript. Comments with a/*!prefix and JSDoc needed for declarations are handled by their own rules, so test before relying on it.targetandmodulechange the syntax of the output, not only its folder. Atargetlower than your runtime supports produces larger, slower code with rewritten classes or async functions.isolatedModulesandverbatimModuleSyntaxmake each file safe to convert on its own. Turn them on when a separate tool such as esbuild or Babel performs the type stripping, because those tools cannot see other files' types.
Common errors
- Output exists despite errors.
noEmitOnErroris off. A pipeline that tests only fordist/index.jspasses broken builds. Check the exit code instead. - Output nested one folder too deep. The inferred
rootDirmoved up because a file outsidesrcwas included. SetrootDirand fixinclude. - Stack traces show
distlines. EithersourceMapis off, or Node was started without--enable-source-maps. - Deleted source file still runs. Stale output stays in
dist. Clean before building. - TS5053 style option conflicts. Combinations such as
sourceMapwithinlineSourceMapare rejected at startup. Choose one. - No output after switching to a bundler setup.
noEmit: trueis working as designed. The bundler writes the JavaScript.
Exercise
A project's tsconfig.json sets "noEmit": true. A teammate runs npx tsc and then node dist/index.js, and gets "Cannot find module". What happened, and what would you change so the same command produces output while the editor keeps using the non-emitting config?
Show answer
noEmit: true makes tsc check types only, so dist was never written. Create a second config, for example tsconfig.build.json, that uses "extends": "./tsconfig.json" and sets "noEmit": false, then build with npx tsc -p tsconfig.build.json. The base config stays non-emitting for the editor and for tsc --noEmit.
Exercise
Your release build must never ship code that has type errors, and production stack traces must point to the original TypeScript lines. Which options do you set in the tsconfig, and what do you add to the command that starts the program?
Show answer
Set "noEmitOnError": true so no files are written when any type error exists, and "sourceMap": true so each .js file gets a .js.map. Start the program with node --enable-source-maps dist/index.js, because Node ignores source maps in stack traces without that flag. Also clear the old dist folder before building, so a blocked build does not leave stale output that could still run.