Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
1 min readTypeScript

Annotate exports for isolated declaration emit

Use isolatedDeclarations to find exports that need annotations before a file-by-file tool can emit declaration files for your TypeScript library.

Your library emits JavaScript with one tool and declarations with TypeScript. You want a declaration emitter that can work on each source file in isolation. Give it a public signature it can read from the file.

Find the export that needs a type

Save this as index.ts. The public function returns a value whose type comes from a call inside its body.

export function readPort(raw: string) {
  const port = Number.parseInt(raw, 10);
  return port;
}

With the usual declaration emit, TypeScript can infer that readPort returns a number.

Save this tsconfig.json alongside it, or merge the compiler options into your library's existing declaration config. Keep an explicit file list for this example so the command checks the file you're editing.

{
  "compilerOptions": {
    "declaration": true,
    "emitDeclarationOnly": true,
    "isolatedDeclarations": true,
    "outDir": "dist"
  },
  "files": ["index.ts"]
}

Run pnpm exec tsc with TypeScript 5.5 or later installed. You’ll see TS9007 asking for an explicit return type on readPort.

Put the type on the export

The checker can follow port to Number.parseInt. A declaration tool that reads only the syntax of this file needs the return type where it can copy it into the declaration.

export function readPort(raw: string): number {
  const port = Number.parseInt(raw, 10);
  return port;
}

Replace index.ts with this version and run the command again. In dist/index.d.ts, the signature is export declare function readPort(raw: string): number;.

Leave the local port inferred. The declaration contains the signature and omits the body. Some exports, such as a constant initialized to a number literal, already give the emitter enough information.

Keep the checker in the build

The isolated declarations flag requires declaration or composite. emitDeclarationOnly is separate. It tells TypeScript to emit declarations without JavaScript in this example.

The flag adds diagnostics and keeps the standard declaration emitter. If you switch to a file-by-file emitter, keep a separate type check in CI to catch mismatches between annotations and implementation.