Sub topic 5
Why declaration emit is expensive
This chapter assumes you can read a tsconfig.json, run tsc from the command line, and know what a .d.ts file is. It explains why producing declaration files costs more than producing JavaScript. The rest of the tutorial's tools (composite projects, isolatedDeclarations, --noCheck) all respond to this cost.
What a declaration file has to contain
A declaration file describes the public surface of a module: the names it exports and the types of those names. It holds no function bodies. Consumers, such as another project or an editor, read it instead of your source.
Some parts of that surface are already written down in your source. Others are not, because you let the compiler infer them. Look at this file:
// user.ts
export interface User {
id: number;
name: string;
}
export function makeUser(id: number, name: string) {
return { id, name, createdAt: new Date() };
}makeUser has no return type annotation. To write its declaration, tsc has to work out the return type from the function body. The emitted user.d.ts looks like this:
export interface User {
id: number;
name: string;
}
export declare function makeUser(id: number, name: string): {
id: number;
name: string;
createdAt: Date;
};The interface was copied as written. The return type of makeUser did not exist in the source. The compiler computed it by checking the function body, which means resolving Date, the parameter types, and the object literal's type.
Why this needs the type checker
Emitting JavaScript is mostly a per-file rewrite. The compiler removes type annotations, lowers syntax for the target, and rewrites module syntax. It does not need to know what any expression's type is. This is why single-file tools such as ts.transpileModule or Babel can produce JavaScript from TypeScript.
Declaration emit is different. Each time it meets a position with no annotation, it must ask the type checker for the type, and then print that type as source text. The table compares the two.
| Aspect | JavaScript emit | Declaration emit |
|---|---|---|
| Input needed | The syntax tree of one file | The syntax tree plus type information |
| Type checker required | No | Yes, for every inferred type |
| Reads other files | No | Yes, when a type comes from an import |
| Can run per file in isolation | Yes | Not by default |
| Output depends on | The file's own text | The file's text and the text of its dependencies |
The last row has a practical consequence. Editing a file that user.ts imports can change the .d.ts of user.ts, even though user.ts itself did not change.
Inference crosses file boundaries
Here is a two-file example.
// defaults.ts
export const defaults = { retries: 3, timeout: 1000 };// client.ts
import { defaults } from "./defaults";
export const retryLimit = defaults.retries;
export function getTimeout() {
return defaults.timeout;
}To emit client.d.ts, the compiler must know the type of defaults from another file. It loads defaults.ts, infers { retries: number; timeout: number }, and then resolves the property accesses. The result is:
export declare const retryLimit: number;
export declare function getTimeout(): number;If defaults.ts later changes timeout to a string, client.d.ts changes to string without any edit to client.ts. A tool that looked only at client.ts could not have produced the right output.
In a real codebase the chain is longer. An inferred type may mention a generic from a library, which in turn mentions types from other packages. The checker has to resolve all of them, and each resolution can load more files into the program.
Naming the inferred type can fail
Printing a type as text is not always possible. The emitter can only write a type if it can name every piece of it from the declaration file's location. Suppose an inferred type refers to an interface declared in a nested dependency that your file never imports. The compiler may have to add an import to the .d.ts or write an import("...") type. When it cannot do that portably, it reports an error such as this one:
error TS2742: The inferred type of 'handler' cannot be named without a reference to
'../node_modules/some-lib/dist/internal'. This is likely not portable.
A type annotation is necessary.These errors show up only when declaration or composite is on. Code that compiles fine without declarations can fail once you turn them on. The fix is nearly always an explicit type annotation, which is the same fix that isolatedDeclarations later demands everywhere.
Where the time goes
A tsc run has four phases: parse, bind, check, and emit. Declaration emit sits across the last two. It uses the checker, so it can force type resolution of expressions that nothing else asked about. It also runs a printer that turns types into text.
Three effects make it costly in large projects:
- Whole-program dependence. The checker is one shared structure for the program. Declaration emit for any file can pull in types from many others, so the work does not split into independent per-file jobs.
- Large printed types. An inferred type from a heavily generic library can expand to hundreds of lines of text. Printing it and then re-parsing it in every consumer costs time at both ends.
- Invalidation fan-out. A change in an upstream file can alter the
.d.tsof many downstream files. The incremental builder tracks a signature (a hash) of each file's declaration output to decide what to recheck. A change to an inferred type changes the signature and triggers more rechecking than a change that leaves the public surface alone.
The third point is why explicit annotations speed up builds even outside isolatedDeclarations. An annotated export has a signature that depends only on the annotation.
Measuring the declaration cost
Before changing anything, measure. The --extendedDiagnostics flag prints the time spent in each phase. Run the build once without declarations and once with them, and compare the emit and check lines.
# Baseline: check only, no output
tsc -p . --noEmit --extendedDiagnostics
# Same program, emitting only declaration files
tsc -p . --declaration --emitDeclarationOnly --extendedDiagnosticsLook at three lines in the output: Check time, Emit time, and Total time. Run each command more than once, because the first run after a change includes cold file system caches. If the second command is clearly slower in Emit time, declaration emit is a real part of your cost. If the numbers are close, a different optimization will help more.
What this means for the tools in this tutorial
Each later chapter targets one part of the problem described above.
- Incremental builds avoid redoing the check and emit work for files whose inputs and dependency signatures did not change.
- Composite projects and references split the program into smaller units. A consumer reads a library's
.d.tsoutput and does not re-check its source. isolatedDeclarationsmoves the type information into annotations that you write, so a declaration can be produced from one file alone.--noCheckand third-party emitters build on that guarantee. Once emit no longer needs the checker, it can run separately and in parallel.
Common mistakes
- Assuming
declaration: trueis free. It adds checker work and the possibility of TS2742-style errors. Measure it. - Treating a slow emit as a parsing problem. Parse and bind rarely dominate. Declaration emit cost shows up under check and emit.
- Annotating everything by hand to fix speed. Annotate exported APIs first. Internal, non-exported code is not part of the declaration output and gains nothing from annotation.
- Comparing a single run each. Timings vary between runs. Repeat each command and compare typical values.
Summary
Declaration emit turns your module's public surface into text. Where you wrote no annotation, that text comes from type inference, which uses the type checker and can read many other files. This is why it cannot run file by file by default, why a distant edit can change a .d.ts, and why large inferred types are slow to print. The next chapters show how to reuse past work and how to make declarations derivable from one file.
Exercise
A file a.ts contains export const limits = { max: 10 };. File b.ts contains import { limits } from "./a"; export const cap = limits.max;. You compile with declaration: true. (1) What does b.d.ts declare for cap? (2) You change a.ts to { max: "10" } and do not touch b.ts. Does b.d.ts change? (3) What single edit to b.ts would make its declaration independent of a.ts?
Show answer
(1) export declare const cap: number; because the checker infers number from limits.max. (2) Yes. The inferred type of cap becomes string, so b.d.ts changes even though b.ts did not change. (3) Add an explicit annotation, export const cap: number = limits.max;. The declaration then comes from the annotation and no longer depends on the type of limits.
Exercise
Give two reasons declaration emit cannot simply run per file in parallel by default, and name the compiler flag that shows the time spent in each build phase.
Show answer
First, inferred types need the type checker, which is a single shared structure for the whole program. Second, an inferred type can come from imported files, so one file's output depends on the contents of other files. The flag is --extendedDiagnostics.