Sub topic 9
Writing the annotations isolatedDeclarations requires
This chapter assumes you have read the earlier chapters on declaration emit and on what isolatedDeclarations guarantees. You should be comfortable with .d.ts files, with export syntax, and with reading tsc error output. The goal here is practical. You will learn which exported declarations need an explicit type, how to write the annotation, and which shortcuts the compiler accepts.
The rule behind every error
With isolatedDeclarations on, tsc must be able to write the .d.ts entry for an exported declaration by looking only at the file that contains it. It may not follow imports or run type inference across files.
This gives one test for any export: can the type be read directly from the syntax, without evaluating anything? A literal such as "viewer" passes. A call such as loadConfig() fails, because the result type lives in another declaration. Everything below applies that test to different kinds of declaration.
Turning the check on
isolatedDeclarations requires either declaration or composite to be enabled. Without one of them, tsc reports a configuration error. To list every violation without writing files, run this command:
tsc -p . --isolatedDeclarations --noEmitEach violation appears as a normal diagnostic with a code in the TS90xx range. For example, a function with no return type reports "Function must have an explicit return type annotation with --isolatedDeclarations", and an exported variable with an uninferable initializer reports "Variable must have an explicit type annotation with --isolatedDeclarations". In an editor, the quick fix "Add annotation" writes the type for you, using the type the compiler currently infers.
What needs an annotation
| Exported construct | Annotation needed? | How to fix |
|---|---|---|
| Function or method return type | Always | Write `: ReturnType` after the parameters |
| Function parameters | Yes, but `noImplicitAny` already requires it | Write the parameter types |
| `const` initialized with a literal | No | None |
| Object literal of literals | No | None |
| Object literal with a spread or a call inside | Yes | Annotate the variable |
| Array literal | Yes, unless written `as const` | Annotate, or add `as const` |
| `const` initialized from a function call | Yes | Annotate the variable |
| Class property with a non-literal initializer | Yes | Annotate the property |
| Getter and setter pair | One of the two | Annotate the getter's return type or the setter's parameter |
| Private class members | No | None, because the `.d.ts` hides their types |
| `export default <expression>` | Yes, for anything except a name | Assign to an annotated `const`, then export the name |
Functions and arrow functions
Parameters have always needed types under strict. The new requirement is the return type, which the compiler used to infer from the function body. That body inference is the cross-file work the option forbids.
An async function returns a Promise, so you write the Promise type yourself. For an arrow function assigned to an exported const, you can annotate the arrow itself or annotate the variable.
export interface User {
id: number;
name: string;
}
export async function fetchUser(id: number): Promise<User> {
return { id, name: `user-${id}` };
}
// Annotating the arrow function is enough:
export const double = (n: number): number => n * 2;
// Annotating the variable works too, and the arrow can stay bare:
export const triple: (n: number) => number = (n) => n * 3;Choose the style that matches your codebase. Annotating the arrow keeps the signature next to the parameter names. Annotating the variable lets you reuse a named function type.
Variables and object literals
A const initialized with a string, number, boolean, or template literal needs nothing, because the type is the literal itself. An object literal whose members are all simple also needs nothing. Two things break the rule: a value that comes from a call, and a spread of another object. The spread is the usual surprise, because it works fine in ordinary compilation.
export interface Options {
retries: number;
verbose: boolean;
}
const base = { retries: 3 };
// Error with isolatedDeclarations: spread assignments cannot be inferred
// export const options = { ...base, verbose: true };
// Fixed: the variable carries its own type
export const options: Options = { ...base, verbose: true };
// Arrays: a mutable array has no single obvious type, so mark it const
export const ROLES = ["admin", "editor", "viewer"] as const;Using as const changes the type to a readonly tuple of literals. That is a different type from string[], so callers that push to the array or expect string[] will break. When you want a plain string[], annotate instead: export const names: string[] = ["a", "b"];.
A type assertion such as loadConfig() as Config is also accepted. It satisfies the rule, but it tells the compiler to trust you instead of checking the value, so a real annotation is safer.
Classes
Public and protected members are part of the class's declaration, so they follow the same rules. Private members (both private and #name) are emitted without their types, so they are exempt.
export interface User {
id: number;
name: string;
}
export class Registry {
// Literal initializer: fine without an annotation
count = 0;
// A constructor call is not readable from syntax, so annotate
readonly users: Map<number, User> = new Map();
// Private: the .d.ts shows only "private cache;"
private cache = new Map<number, string>();
add(user: User): void {
this.users.set(user.id, user);
this.cache.set(user.id, user.name);
this.count += 1;
}
// Accessors need a type on the getter
get size(): number {
return this.users.size;
}
}Methods need explicit return types, including void. Forgetting : void on a method that returns nothing is a common cause of errors in a first pass.
Default exports
export default followed by an expression such as an object literal with calls, or a function call, cannot be written into the .d.ts from syntax alone. Give the value a name and a type, then export the name.
export interface Settings {
port: number;
hosts: string[];
}
function defaultHosts(): string[] {
return ["localhost"];
}
const settings: Settings = { port: 8080, hosts: defaultHosts() };
export default settings;Exporting a plain identifier is accepted, because the .d.ts can refer to the name and its declared type.
Errors you will commonly meet
- Re-exporting a computed value.
export const handler = createHandler(config)fails because the type comes fromcreateHandler. Annotate with the type that function returns, for exampleHandler. If that type is not exported, export it from where it is defined. - Inferred unions and conditional returns. A function that returns
stringin one branch andundefinedin another used to getstring | undefinedfor free. Write it out:: string | undefined. - Long object types. If an annotation is large, define a named
interfaceortypeand use it. The declaration file gets shorter, and so does your source. - Using
ReturnType<typeof fn>as the annotation. This is allowed whenfnis in the same file or imported, but it brings back the dependency you were trying to remove, and readers must chase the reference. A named type is clearer. - Annotation that differs from the inferred type. If you write a wider type than the compiler had inferred, the
.d.tschanges, and consumers see the wider type. Compare the.d.tsoutput before and after during a migration.
Checking your work
Annotations do not change emitted JavaScript. They can change emitted declarations, so verify with two commands: one for errors and one for the declaration output.
tsc -p . --isolatedDeclarations --noEmit
tsc -p . --declaration --emitDeclarationOnly --outDir distThe first must exit with no TS90xx errors. After the second, read a few files in dist that you changed. Each exported name should have the type you wrote, and no any should have appeared.
Summary of the working model
- The compiler needs every exported type to be readable from the file's own syntax.
- Literals, objects of literals,
as constarrays, and private members need nothing. - Functions need return types. Variables and properties that come from calls, spreads, or
newneed explicit types. - Annotations affect declarations, not runtime behavior. Verify them by running
tsc --isolatedDeclarations --noEmitand reading the emitted.d.ts.
Exercise
The following module fails with isolatedDeclarations on. Find the three declarations that need changes, and write the corrected code.
export const defaults = { retries: 3 };
export const merged = { ...defaults, timeout: 1000 };
export function label(n: number) {
return item-${n};
}
export const created = new Date();
Show answer
The declaration of defaults is fine, because an object of literals is readable from syntax. The other three exports need types. merged uses a spread, label has no return type, and created comes from a constructor call.
interface Merged {
retries: number;
timeout: number;
}
export const defaults = { retries: 3 };
export const merged: Merged = { ...defaults, timeout: 1000 };
export function label(n: number): string {
return item-${n};
}
export const created: Date = new Date();
Here merged is the only declaration with a spread, so it is the one an experienced reader would expect to fail. Exporting Merged as well is optional, but it helps consumers that want to name the type.
Exercise
A class has the members private cache = new Map<string, number>(); and items = new Set<string>();. Which one needs an annotation under isolatedDeclarations, and why?
Show answer
Only items needs one, for example items: Set<string> = new Set();. The items property is public, so its type appears in the .d.ts, and new Set() does not show the element type from syntax alone. The cache property is private, and declaration files omit the types of private members, so no annotation is needed.