Sub topic 3
Writing the annotations `isolatedDeclarations` requires
Assume you know basic TypeScript types, can run tsc, and can edit tsconfig.json. This chapter focuses on declaration generation, not general type-checking performance.
Required annotations
isolatedDeclarations guarantees that TypeScript can derive each declaration file from one source file at a time. This enables parallel declaration emitters, but the compiler cannot infer public types from other files.
Enable it with declaration output:
{
"compilerOptions": {
"declaration": true,
"isolatedDeclarations": true,
"outDir": "dist"
}
}Exported functions need explicit return types. Exported values whose types come from a function call need explicit variable types.
export interface Config {
retries: number;
}
declare function loadConfig(): Config;
export function add(a: number, b: number): number {
return a + b;
}
export const config: Config = loadConfig();The annotations describe the public API and make declaration generation independent of another file's inferred types.
Rolling out the option
In an existing project, enable the option in a branch or package at a time. Run the compiler and fix reported errors by annotating exported functions, classes, variables, and accessors.
Keep internal implementation details inferred when possible. Focus on exported declarations first. Review generated .d.ts files because adding an annotation can expose an unintended public type.
A useful rollout sequence is:
- Enable
declarationand inspect current output. - Enable
isolatedDeclarations. - Fix annotation errors.
- Run the normal type checker and declaration tests.
- Enable the option for more packages.
Emitting declarations without type checking
TypeScript 5.5 added --noCheck. Pair it with isolated declarations when a fast emit step is useful:
tsc --noCheck --declaration --emitDeclarationOnly --outDir dist
tsc --noEmitThe first command emits declarations without the normal type-checking pass. The second command remains responsible for finding type errors. Run both in CI or in separate development tasks.
Generating declarations in parallel
Because every exported type is explicit, a declaration emitter can process source files independently. Third-party build tools can then generate .d.ts files in parallel with JavaScript bundling. Check that the tool supports your TypeScript syntax and compare its output with tsc before adopting it.
Reusing build state in CI
Cache .tsbuildinfo, declaration output, and other build artifacts only when the cache key includes the lockfile, TypeScript version, compiler configuration, and relevant source inputs. A stale cache can produce confusing results, so CI must still validate the final build.
Exercise
Why does an exported function need an explicit return type with isolatedDeclarations?
Show answer
Its declaration must be generated from that file alone, without inferring the return type through other source files.