Skip to content

Declarations & Package Exports

The Course
•
20 min study

A declaration file, ending .d.ts, describes exported types and values without implementing them. With declaration:true, the compiler emits these files beside the JavaScript. A consumer can check against them while Node executes the .js modules.

The download has a public index.ts exporting values normally and types with export type. package.json points its types export to dist/index.d.ts and import export to dist/index.js. The package is private, and all exercises remain local; no publication is required.

Build first, then check consumer.ts in a separate noEmit configuration. Its import uses the package's own name, resolved through exports, so missing public exports and weakened generated declarations are visible. Importing internal source files would skip this packaging boundary.

Do not hand-edit generated declarations. Edit source, rebuild, then check the consumer and run the JavaScript tests. The browser editors combine definitions in one module; relative imports and package-resolution exercises belong in the downloaded local project.

Follow one function through compilation

These are local-file listings to compare, not three programs to paste into one editor. Source contains both the contract and implementation:

label.ts — authored source

TypeScript
export type Book = { readonly title: string };

export function label(book: Book): string {
  return book.title.trim();
}

label.d.ts — generated contract

TypeScript
export type Book = { readonly title: string };

export declare function label(book: Book): string;

label.js — generated implementation

JavaScript
export function label(book) {
  return book.title.trim();
}

The checker reads the declaration's parameter and return types. Node executes the JavaScript body. The declaration's declare means the function exists in the implementation; it does not implement the function. The alias and annotations disappear from JavaScript.

Read the package boundary

The gateway's index.ts is a public entry point, often called a barrel. A re-export forwards an existing export rather than duplicating its definition:

TypeScript
export { createGateway } from "./gateway.js";
export type { AppEvent } from "./domain.js";

The type-only line disappears at runtime. The package.json below selects the built entry points; "." means the root import such as import { createGateway } from "typed-event-gateway", not a request for a relative file:

JSON
{
  "name": "typed-event-gateway",
  "private": true,
  "type": "module",
  "exports": {
    ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" }
  }
}

Here name also lets this package import itself for the consumer test. The types target is for checking, the import target is for ES module execution, and private prevents accidental npm publication. This is local package resolution, not a network download.

The declaration-files introduction gives more background. You can complete the browser exercises first and try the optional local workflow on Day 7.

StepCommand inside the extracted folderWhat it checks
Buildnpm run buildSource, emitted JavaScript and declarations
Public consumernpm run checkBuild, then consumer.ts against the declarations
Runtimenpm testBoth previous layers, then public JavaScript behavior

Predict, check, and run

Write the output before running. Use Check types first, then Check & run. Types disappear at runtime: explain both what the compiler checks and what the code actually does. Each editor is an independent ES module; await asynchronous work explicitly.

Predict, then runTypeScript
type Publisher<T> = { publish: (value: T) => boolean };

function usePublisher(publisher: Publisher<string>): boolean {
  return publisher.publish("Types");
}

const implementation: Publisher<string> = {
  publish: value => value.length > 0
};

console.log(usePublisher(implementation));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
true

Read the compiler error

Predict the rejected relationship before checking. Read the real diagnostic and its source location; fix the contract or the value instead of hiding it with an assertion.

Find and fix the type errorTypeScript
type Publisher<T> = { publish: (value: T) => boolean };

const publisher: Publisher<number> = { publish: value => String(value) };

console.log(publisher);

Enable JavaScript to edit and type-check this example.

Check your diagnosis

The key line is TS2322: Type 'string' is not assignable to type 'boolean'. The required type comes from the declaration, so the declaration is the contract and the implementation is what must change.

The implementation returns string while the public declaration promises boolean. A declaration is a contract the implementation must satisfy.

Trace the contract before building

A declaration is what a consumer can learn without reading your implementation. Check exported names, parameter relationships, inferred results, and visibility of internal helper types. A local implementation test may pass even when the published declaration makes a supported call impossible or loses useful inference.

Write a small consumer using only the exported entry point. Check a valid call, an invalid call, and the resulting type of a selected operation. Then verify the runtime package exposes the values that the declaration advertises. Publishing types and publishing JavaScript are connected tasks; neither file alone proves that an installed consumer receives a coherent library.

Build it yourself

Exercise

Declarations & Package Exports: practice

The workspace holds a module, channel.ts. Run it, then write by hand, in a comment under the code, the channel.d.ts that tsc --declaration would emit for it. Decide for each top-level name whether it appears, and if it does, exactly what type it is declared with. Compare your listing with the solution. If you have the local project, check your answer by compiling the file with declaration: true.

Your workspaceTypeScript
export type Channel<T> = {
  readonly name: string;
  publish: (value: T) => boolean;
};

const prefix = "feed:";

function fullName(name: string): string {
  return prefix + name.trim();
}

export function createChannel<T>(
  name: string,
  accept: (value: T) => boolean
): Channel<T> {
  return { name: fullName(name), publish: value => accept(value) };
}

export const defaultName = "events";

export const counts = createChannel("counts", (value: number) => value >= 0);

console.log(counts.name, counts.publish(0), counts.publish(-1));
console.log(createChannel(defaultName, (value: string) => value !== "").name);

// Write channel.d.ts here, as a comment.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

A declaration file holds only what an importer can see: exported names and their types. Anything not exported disappears, and every function body and initializer is replaced by a type.

Hint 2: a first step

Go through the six top-level declarations one at a time. For counts, the declaration needs the type the checker inferred, so hover over it or work it out from the call. For defaultName, remember what a const keeps.

Show one solution
One possible solutionTypeScript
export type Channel<T> = {
  readonly name: string;
  publish: (value: T) => boolean;
};

const prefix = "feed:";

function fullName(name: string): string {
  return prefix + name.trim();
}

export function createChannel<T>(
  name: string,
  accept: (value: T) => boolean
): Channel<T> {
  return { name: fullName(name), publish: value => accept(value) };
}

export const defaultName = "events";

export const counts = createChannel("counts", (value: number) => value >= 0);

console.log(counts.name, counts.publish(0), counts.publish(-1));
console.log(createChannel(defaultName, (value: string) => value !== "").name);

Enable JavaScript to edit and type-check this example.

Text
feed:counts true false
feed:events

The source runs unchanged; the answer is the emitted declaration file:

TypeScript
export type Channel<T> = {
  readonly name: string;
  publish: (value: T) => boolean;
};
export declare function createChannel<T>(
  name: string,
  accept: (value: T) => boolean
): Channel<T>;
export declare const defaultName = "events";
export declare const counts: Channel<number>;

prefix and fullName are not exported, so they are absent: consumers cannot call them, and the declaration does not mention that they exist. The Channel type alias is copied as it is. createChannel keeps its full generic signature and loses its body. defaultName keeps the literal type "events", because a const of a string literal is declared with that literal. counts has no annotation in the source, so the compiler writes the inferred Channel<number>: this is how inference reaches the consumer. Annotating exported values yourself keeps that published type deliberate.

Change it and test it

In a local copy, remove createGateway from index.ts and run npm run check. The build may already fail because main.ts also imports the public entry point; that is an expected public-contract failure, not a broken test setup. Restore the export, rerun check, and inspect how dist/index.d.ts forwards the generated gateway declaration. Never repair a missing export by editing dist directly.

Was this article helpful?

Your response is saved on this device.