TypeScript declaration files let you describe a JavaScript package without rewriting its runtime code. This guide explains when to use .d.ts files, how to write declare module declarations, how to generate and expose types from a TypeScript library, and how to verify that consumers receive the API you intended.
Overview
A declaration file contains type information only. It does not produce JavaScript and it should match the behavior of the implementation that consumers actually run. Declaration files are commonly used in three situations:
- You are consuming an untyped JavaScript dependency and need a local type boundary.
- You maintain a JavaScript package and want to add types without converting the implementation yet.
- You publish a TypeScript package and need to ship generated declarations alongside compiled JavaScript.
The most important rule is to model the public API, not the internal implementation. A declaration that is technically valid but exposes the wrong parameter order, optionality, generic constraint, overload, or module path can give consumers a false sense of safety.
Before choosing a solution, identify the package boundary. For an application dependency, a small ambient declaration may be enough. For a reusable npm library, declarations should generally be maintained as part of the package build and tested from a separate consumer project.
If you are migrating a larger codebase, declaration work can be a useful intermediate step: it gives JavaScript modules a typed interface while implementation files are converted gradually. Pair that work with a strict-mode rollout plan and focused tests rather than treating declarations as a substitute for runtime validation.
Checklist by scenario
Scenario 1: An untyped JavaScript dependency
Start with a local declaration when a dependency has no usable types and you need a safe interface in one application. Create a file such as src/types/legacy-widget.d.ts and declare the module using its exact import specifier:
declare module 'legacy-widget' {
export interface WidgetOptions {
endpoint: string;
retries?: number;
}
export function createWidget(options: WidgetOptions): Widget;
export interface Widget {
start(): Promise<void>;
stop(): void;
}
}
- Confirm that the declaration file is included by the project’s
tsconfig.json. - Match the dependency’s actual default, named, or namespace exports.
- Use
unknowninstead ofanyfor values whose shape is not established. - Add a small usage file or test that imports the package exactly as application code does.
- Record the package version or runtime behavior that the declaration describes.
This approach is intentionally local. If several applications need the same types, move the declaration into a maintained package or contribute types to the dependency’s normal distribution path rather than copying files between repositories.
Scenario 2: A JavaScript package being migrated
If the implementation remains JavaScript, a companion declaration file can describe its public surface. For a CommonJS-style module, the shape might look like this:
declare function createClient(baseUrl: string): Client;
declare namespace createClient {
interface Client {
get<T>(path: string): Promise<T>;
}
}
export = createClient;
The correct syntax depends on the package’s real module behavior. Do not select export default merely because it looks simpler; consumers must be able to import the declaration in the same way that Node.js, a bundler, or the package’s existing documentation permits.
Use this checklist during a gradual migration:
- List every supported entry point, including subpath imports.
- Document the inputs, outputs, thrown errors, callbacks, and side effects that users can observe.
- Convert the declaration and implementation together when a function’s contract is unclear.
- Keep internal helpers unexported unless they are intentionally part of the public API.
- Use consumer tests to prevent a declaration from drifting away from JavaScript behavior.
Scenario 3: Publishing a TypeScript npm library
For a TypeScript library, configure the compiler to emit declarations during the build. A typical library-oriented configuration includes:
{
"compilerOptions": {
"declaration": true,
"declarationMap": true,
"emitDeclarationOnly": false,
"outDir": "dist",
"rootDir": "src"
}
}
The exact settings depend on your build system, but the release should contain compiled JavaScript, declaration files, and any source maps you promise to support. In package.json, expose the intended entry points and types. A simple package may use a types field:
{
"main": "./dist/index.js",
"types": "./dist/index.d.ts"
}
Packages with multiple module formats or subpath exports need a coordinated exports map. Check that each public subpath has a matching runtime target and declaration target. Test the packed artifact with npm pack or an equivalent local installation; testing only the repository source can hide missing files or incorrect paths.
Decision table
| Situation | Preferred starting point | Primary risk |
|---|---|---|
| One app uses an untyped dependency | Local declare module | Declaration describes only an assumed API |
| JavaScript package is being migrated | Companion .d.ts, then gradual source conversion | Types drift from runtime behavior |
| TypeScript package is published | Generated declarations and tested package exports | Consumers cannot resolve or receive the types |
| Several projects need the same definitions | Maintained package or upstream contribution | Copies diverge across repositories |
What to double-check
Exports and module resolution
Verify named exports, default exports, CommonJS assignments, namespace-style APIs, and subpath exports independently. An index declaration cannot describe an entry point that the package does not actually expose. Test both the import syntax and the resolved declaration path in the module configurations your consumers use.
Generics and overloads
Generics should preserve useful relationships between inputs and outputs. For example, get<T>() communicates a caller-selected result type, but it does not validate the response at runtime. If the implementation knows a finite set of result shapes, overloads or constrained generics may be more accurate. Order overloads from the most specific signature to the broadest one, and test calls that should fail as well as calls that should compile.
Optionality and nullability
Distinguish an omitted property from a property whose value is undefined, null, or an empty string when those differences matter. Check compiler settings such as strictNullChecks before publishing assumptions about nullable values. A declaration that makes every field required can be just as misleading as one that makes everything optional.
Runtime boundaries
Declarations disappear at runtime. They cannot confirm JSON payloads, environment variables, database results, or third-party responses. At those boundaries, combine static types with validation or explicit narrowing. For API clients, keep generated or hand-written types aligned with the schema and test representative responses. See this guide to TypeScript API typing for patterns that connect API schemas with client code.
Consumer verification
Create a small fixture that installs the packed library and checks real import statements. Include positive cases, expected compiler failures, generic inference, overload selection, and the package’s supported module formats. Type-focused tests complement runtime tests; this TypeScript testing guide covers broader testing patterns.
Common mistakes
- Using
anyas a permanent placeholder. Start withunknownor a narrower shape and make uncertainty visible to callers. - Declaring the source path instead of the package name. The string in
declare modulemust match the import specifier consumers write. - Publishing declarations without the files. Check the packed tarball, not just the repository tree.
- Assuming generated declarations are automatically correct. Inspect the emitted API and review accidental exports.
- Changing the public type without recognizing the runtime change. A type-only correction can still be breaking if existing consumer code relied on the old contract.
- Testing only the implementation project. Internal path aliases and source files can conceal package export and resolution problems.
- Confusing compile-time claims with runtime checks. A declaration does not parse, validate, or transform data.
When to revisit
Revisit declaration files whenever the public surface changes or the toolchain changes. A practical review trigger list includes:
- A function, class, type, export, or package subpath is added or removed.
- A parameter becomes optional, required, nullable, asynchronous, or generic.
- The package changes its JavaScript output, module format, build directory, or
exportsmap. - A dependency gains official types or changes its runtime API.
- TypeScript, Node.js, the bundler, or the package manager changes module-resolution behavior.
- A release is prepared, especially after dependency upgrades or build-configuration edits.
- Seasonal planning or maintenance cycles begin and ownership of the package is reviewed.
Before publishing, run this short final checklist: build declarations from a clean checkout; inspect the generated files; verify every documented entry point; pack and install the artifact in a consumer fixture; test generics and overloads; confirm expected compiler failures; and compare the declaration with runtime tests. If the package is still being migrated, mark uncertain areas explicitly and replace them as implementation evidence becomes available.
For related cleanup, use a TypeScript utility types reference, review common compiler diagnostics, and keep path aliases consistent across the editor, test runner, bundler, and runtime. A declaration file is reliable when it is treated as a maintained public contract—not as a one-time annotation added at the end of a release.